Coverage Report

Created: 2023-06-20 01:28

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.89.7 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - Read FAQ at http://dearimgui.com/faq
6
// - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
7
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
8
// Read imgui.cpp for details, links and comments.
9
10
// Resources:
11
// - FAQ                   http://dearimgui.com/faq
12
// - Homepage & latest     https://github.com/ocornut/imgui
13
// - Releases & changelog  https://github.com/ocornut/imgui/releases
14
// - Gallery               https://github.com/ocornut/imgui/issues/6478 (please post your screenshots/video there!)
15
// - Wiki                  https://github.com/ocornut/imgui/wiki (lots of good stuff there)
16
// - Glossary              https://github.com/ocornut/imgui/wiki/Glossary
17
// - Issues & support      https://github.com/ocornut/imgui/issues
18
19
// Getting Started?
20
// - For first-time users having issues compiling/linking/running or issues loading fonts:
21
//   please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
22
23
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
24
// See LICENSE.txt for copyright and licensing details (standard MIT License).
25
// This library is free but needs your support to sustain development and maintenance.
26
// Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.com".
27
// Individuals: you can support continued development via donations. See docs/README or web page.
28
29
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
30
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
31
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
32
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
33
// to a better solution or official support for them.
34
35
/*
36
37
Index of this file:
38
39
DOCUMENTATION
40
41
- MISSION STATEMENT
42
- CONTROLS GUIDE
43
- PROGRAMMER GUIDE
44
  - READ FIRST
45
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
46
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
47
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
48
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
49
- API BREAKING CHANGES (read me when you update!)
50
- FREQUENTLY ASKED QUESTIONS (FAQ)
51
  - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
52
53
CODE
54
(search for "[SECTION]" in the code to find them)
55
56
// [SECTION] INCLUDES
57
// [SECTION] FORWARD DECLARATIONS
58
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
59
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
60
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
61
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
62
// [SECTION] MISC HELPERS/UTILITIES (File functions)
63
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
64
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
65
// [SECTION] ImGuiStorage
66
// [SECTION] ImGuiTextFilter
67
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
68
// [SECTION] ImGuiListClipper
69
// [SECTION] STYLING
70
// [SECTION] RENDER HELPERS
71
// [SECTION] INITIALIZATION, SHUTDOWN
72
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
73
// [SECTION] INPUTS
74
// [SECTION] ERROR CHECKING
75
// [SECTION] LAYOUT
76
// [SECTION] SCROLLING
77
// [SECTION] TOOLTIPS
78
// [SECTION] POPUPS
79
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
80
// [SECTION] DRAG AND DROP
81
// [SECTION] LOGGING/CAPTURING
82
// [SECTION] SETTINGS
83
// [SECTION] LOCALIZATION
84
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
85
// [SECTION] DOCKING
86
// [SECTION] PLATFORM DEPENDENT HELPERS
87
// [SECTION] METRICS/DEBUGGER WINDOW
88
// [SECTION] DEBUG LOG WINDOW
89
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
90
91
*/
92
93
//-----------------------------------------------------------------------------
94
// DOCUMENTATION
95
//-----------------------------------------------------------------------------
96
97
/*
98
99
 MISSION STATEMENT
100
 =================
101
102
 - Easy to use to create code-driven and data-driven tools.
103
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
104
 - Easy to hack and improve.
105
 - Minimize setup and maintenance.
106
 - Minimize state storage on user side.
107
 - Minimize state synchronization.
108
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
109
 - Efficient runtime and memory consumption.
110
111
 Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes:
112
113
 - Doesn't look fancy, doesn't animate.
114
 - Limited layout features, intricate layouts are typically crafted in code.
115
116
117
 CONTROLS GUIDE
118
 ==============
119
120
 - MOUSE CONTROLS
121
   - Mouse wheel:                   Scroll vertically.
122
   - SHIFT+Mouse wheel:             Scroll horizontally.
123
   - Click [X]:                     Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
124
   - Click ^, Double-Click title:   Collapse window.
125
   - Drag on corner/border:         Resize window (double-click to auto fit window to its contents).
126
   - Drag on any empty space:       Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
127
   - Left-click outside popup:      Close popup stack (right-click over underlying popup: Partially close popup stack).
128
129
 - TEXT EDITOR
130
   - Hold SHIFT or Drag Mouse:      Select text.
131
   - CTRL+Left/Right:               Word jump.
132
   - CTRL+Shift+Left/Right:         Select words.
133
   - CTRL+A or Double-Click:        Select All.
134
   - CTRL+X, CTRL+C, CTRL+V:        Use OS clipboard.
135
   - CTRL+Z, CTRL+Y:                Undo, Redo.
136
   - ESCAPE:                        Revert text to its original value.
137
   - On OSX, controls are automatically adjusted to match standard OSX text editing shortcuts and behaviors.
138
139
 - KEYBOARD CONTROLS
140
   - Basic:
141
     - Tab, SHIFT+Tab               Cycle through text editable fields.
142
     - CTRL+Tab, CTRL+Shift+Tab     Cycle through windows.
143
     - CTRL+Click                   Input text into a Slider or Drag widget.
144
   - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
145
     - Tab, SHIFT+Tab:              Cycle through every items.
146
     - Arrow keys                   Move through items using directional navigation. Tweak value.
147
     - Arrow keys + Alt, Shift      Tweak slower, tweak faster (when using arrow keys).
148
     - Enter                        Activate item (prefer text input when possible).
149
     - Space                        Activate item (prefer tweaking with arrows when possible).
150
     - Escape                       Deactivate item, leave child window, close popup.
151
     - Page Up, Page Down           Previous page, next page.
152
     - Home, End                    Scroll to top, scroll to bottom.
153
     - Alt                          Toggle between scrolling layer and menu layer.
154
     - CTRL+Tab then Ctrl+Arrows    Move window. Hold SHIFT to resize instead of moving.
155
   - Output when ImGuiConfigFlags_NavEnableKeyboard set,
156
     - io.WantCaptureKeyboard flag is set when keyboard is claimed.
157
     - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
158
     - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
159
160
 - GAMEPAD CONTROLS
161
   - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
162
   - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
163
   - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
164
   - Backend support: backend needs to:
165
      - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
166
      - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
167
        Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
168
      - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
169
   - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
170
     with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
171
172
 - REMOTE INPUTS SHARING & MOUSE EMULATION
173
   - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
174
   - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
175
     in order to share your PC mouse/keyboard.
176
   - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
177
   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
178
     Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
179
     When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
180
     When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
181
     (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
182
     (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
183
     to set a boolean to ignore your other external mouse positions until the external source is moved again.)
184
185
186
 PROGRAMMER GUIDE
187
 ================
188
189
 READ FIRST
190
 ----------
191
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
192
 - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or
193
   destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, fewer bugs.
194
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
195
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
196
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
197
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
198
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
199
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
200
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
201
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
202
 - This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
203
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
204
   If you get an assert, read the messages and comments around the assert.
205
 - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
206
 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
207
   See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
208
   However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
209
 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
210
211
212
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
213
 ----------------------------------------------
214
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
215
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
216
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
217
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
218
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
219
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
220
   likely be a comment about it. Please report any issue to the GitHub page!
221
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
222
 - Try to keep your copy of Dear ImGui reasonably up to date.
223
224
225
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
226
 ---------------------------------------------------------------
227
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
228
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
229
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
230
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
231
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
232
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
233
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
234
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
235
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
236
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
237
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
238
239
240
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
241
 --------------------------------------
242
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
243
 The sub-folders in examples/ contain examples applications following this structure.
244
245
     // Application init: create a dear imgui context, setup some options, load fonts
246
     ImGui::CreateContext();
247
     ImGuiIO& io = ImGui::GetIO();
248
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
249
     // TODO: Fill optional fields of the io structure later.
250
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
251
252
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
253
     ImGui_ImplWin32_Init(hwnd);
254
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
255
256
     // Application main loop
257
     while (true)
258
     {
259
         // Feed inputs to dear imgui, start new frame
260
         ImGui_ImplDX11_NewFrame();
261
         ImGui_ImplWin32_NewFrame();
262
         ImGui::NewFrame();
263
264
         // Any application code here
265
         ImGui::Text("Hello, world!");
266
267
         // Render dear imgui into screen
268
         ImGui::Render();
269
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
270
         g_pSwapChain->Present(1, 0);
271
     }
272
273
     // Shutdown
274
     ImGui_ImplDX11_Shutdown();
275
     ImGui_ImplWin32_Shutdown();
276
     ImGui::DestroyContext();
277
278
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
279
280
     // Application init: create a dear imgui context, setup some options, load fonts
281
     ImGui::CreateContext();
282
     ImGuiIO& io = ImGui::GetIO();
283
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
284
     // TODO: Fill optional fields of the io structure later.
285
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
286
287
     // Build and load the texture atlas into a texture
288
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
289
     int width, height;
290
     unsigned char* pixels = nullptr;
291
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
292
293
     // At this point you've got the texture data and you need to upload that to your graphic system:
294
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
295
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
296
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
297
     io.Fonts->SetTexID((void*)texture);
298
299
     // Application main loop
300
     while (true)
301
     {
302
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
303
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
304
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
305
        io.DisplaySize.x = 1920.0f;             // set the current display width
306
        io.DisplaySize.y = 1280.0f;             // set the current display height here
307
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
308
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
309
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
310
311
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
312
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
313
        ImGui::NewFrame();
314
315
        // Most of your application code here
316
        ImGui::Text("Hello, world!");
317
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
318
        MyGameRender(); // may use any Dear ImGui functions as well!
319
320
        // Render dear imgui, swap buffers
321
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
322
        ImGui::EndFrame();
323
        ImGui::Render();
324
        ImDrawData* draw_data = ImGui::GetDrawData();
325
        MyImGuiRenderFunction(draw_data);
326
        SwapBuffers();
327
     }
328
329
     // Shutdown
330
     ImGui::DestroyContext();
331
332
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
333
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
334
 Please read the FAQ and example applications for details about this!
335
336
337
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
338
 ---------------------------------------------
339
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
340
341
    void MyImGuiRenderFunction(ImDrawData* draw_data)
342
    {
343
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
344
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
345
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
346
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
347
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
348
       ImVec2 clip_off = draw_data->DisplayPos;
349
       for (int n = 0; n < draw_data->CmdListsCount; n++)
350
       {
351
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
352
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
353
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
354
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
355
          {
356
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
357
             if (pcmd->UserCallback)
358
             {
359
                 pcmd->UserCallback(cmd_list, pcmd);
360
             }
361
             else
362
             {
363
                 // Project scissor/clipping rectangles into framebuffer space
364
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
365
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
366
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
367
                     continue;
368
369
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
370
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
371
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
372
                 // - Clipping coordinates are provided in imgui coordinates space:
373
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
374
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
375
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
376
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
377
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
378
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
379
380
                 // The texture for the draw call is specified by pcmd->GetTexID().
381
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
382
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
383
384
                 // Render 'pcmd->ElemCount/3' indexed triangles.
385
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
386
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
387
             }
388
          }
389
       }
390
    }
391
392
393
 API BREAKING CHANGES
394
 ====================
395
396
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
397
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
398
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
399
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
400
401
(Docking/Viewport Branch)
402
 - 2023/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
403
                          - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
404
                            you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
405
                          - likewise io.MousePos and GetMousePos() will use OS coordinates.
406
                            If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
407
408
 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
409
 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
410
                           - ListBoxHeader()  -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
411
                           - ListBoxFooter()  -> use EndListBox()
412
 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
413
 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
414
 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
415
                           - ImGuiSliderFlags_ClampOnInput        -> use ImGuiSliderFlags_AlwaysClamp
416
                           - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
417
                           - ImDrawList::AddBezierCurve()         -> use ImDrawList::AddBezierCubic()
418
                           - ImDrawList::PathBezierCurveTo()      -> use ImDrawList::PathBezierCubicCurveTo()
419
 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
420
 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
421
 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
422
                         Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
423
                         it has been frequently requested by people to use our own. We had an opt-in define which was
424
                         previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
425
                           - OK:     #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
426
                           - Error:  #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
427
 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
428
 - 2022/10/26 (1.89)   - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
429
 - 2022/10/12 (1.89)   - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
430
 - 2022/09/26 (1.89)   - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
431
                           - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
432
                           - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
433
                           - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
434
                           - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
435
                         the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
436
                         the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
437
                         exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
438
 - 2022/09/20 (1.89)   - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
439
                         this will require uses of legacy backend-dependent indices to be casted, e.g.
440
                            - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
441
                            - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
442
                            - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
443
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
444
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
445
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
446
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
447
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
448
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
449
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
450
                         - previously this would make the window content size ~200x200:
451
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
452
                         - instead, please submit an item:
453
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
454
                         - alternative:
455
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
456
                         - content size is now only extended when submitting an item!
457
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
458
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
459
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
460
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
461
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
462
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
463
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
464
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
465
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
466
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
467
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
468
                        - Official backends from 1.87+                  -> no issue.
469
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
470
                        - Custom backends not writing to io.NavInputs[] -> no issue.
471
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
472
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
473
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
474
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
475
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
476
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
477
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
478
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
479
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
480
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
481
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
482
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
483
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
484
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
485
                       read https://github.com/ocornut/imgui/issues/4921 for details.
486
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
487
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
488
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
489
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
490
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
491
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
492
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
493
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
494
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
495
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
496
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
497
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
498
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
499
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
500
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
501
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
502
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
503
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
504
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
505
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
506
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
507
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
508
                        - if you are using official backends from the source tree: you have nothing to do.
509
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
510
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
511
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
512
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
513
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
514
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
515
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
516
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
517
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
518
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
519
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
520
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
521
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
522
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
523
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
524
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
525
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
526
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
527
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
528
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
529
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
530
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
531
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
532
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
533
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
534
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
535
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
536
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
537
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
538
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
539
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
540
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
541
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
542
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
543
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
544
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
545
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
546
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
547
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
548
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
549
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
550
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
551
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
552
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
553
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
554
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
555
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
556
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
557
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
558
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
559
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
560
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
561
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
562
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
563
                       - if you omitted the 'power' parameter (likely!), you are not affected.
564
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
565
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
566
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
567
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
568
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
569
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
570
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
571
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
572
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
573
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
574
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
575
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
576
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
577
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
578
                       - ShowTestWindow()                    -> use ShowDemoWindow()
579
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
580
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
581
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
582
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
583
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
584
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
585
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
586
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
587
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
588
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
589
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
590
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
591
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
592
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
593
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
594
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
595
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
596
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
597
                       - ImFont::Glyph                       -> use ImFontGlyph
598
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
599
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
600
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
601
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
602
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
603
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
604
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
605
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
606
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
607
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
608
                       Please reach out if you are affected.
609
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
610
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
611
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
612
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
613
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
614
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
615
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
616
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
617
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
618
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
619
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
620
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
621
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
622
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
623
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
624
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
625
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
626
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
627
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
628
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
629
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
630
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
631
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
632
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
633
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
634
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
635
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
636
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
637
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
638
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
639
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
640
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
641
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
642
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
643
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
644
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
645
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
646
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
647
                       consistent with other functions. Kept redirection functions (will obsolete).
648
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
649
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
650
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
651
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
652
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
653
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
654
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
655
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
656
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
657
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
658
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
659
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
660
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
661
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
662
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
663
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
664
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
665
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
666
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
667
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
668
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
669
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
670
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
671
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
672
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
673
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
674
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
675
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
676
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
677
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
678
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
679
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
680
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
681
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
682
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
683
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
684
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
685
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
686
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
687
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
688
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
689
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
690
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
691
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
692
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
693
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
694
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
695
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
696
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
697
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
698
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
699
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
700
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
701
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
702
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
703
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
704
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
705
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
706
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
707
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
708
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
709
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
710
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
711
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
712
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
713
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
714
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
715
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
716
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
717
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
718
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
719
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
720
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
721
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
722
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
723
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
724
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
725
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
726
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
727
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
728
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
729
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
730
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
731
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
732
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
733
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
734
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
735
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
736
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
737
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
738
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
739
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
740
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
741
                     - the signature of the io.RenderDrawListsFn handler has changed!
742
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
743
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
744
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
745
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
746
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
747
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
748
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
749
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
750
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
751
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
752
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
753
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
754
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
755
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
756
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
757
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
758
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
759
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
760
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
761
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
762
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
763
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
764
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
765
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
766
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
767
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
768
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
769
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
770
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
771
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
772
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
773
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
774
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
775
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
776
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
777
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
778
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
779
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
780
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
781
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
782
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
783
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
784
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
785
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
786
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
787
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
788
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
789
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
790
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
791
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
792
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
793
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
794
795
796
 FREQUENTLY ASKED QUESTIONS (FAQ)
797
 ================================
798
799
 Read all answers online:
800
   https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
801
 Read all answers locally (with a text editor or ideally a Markdown viewer):
802
   docs/FAQ.md
803
 Some answers are copied down here to facilitate searching in code.
804
805
 Q&A: Basics
806
 ===========
807
808
 Q: Where is the documentation?
809
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
810
    - Run the examples/ and explore them.
811
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
812
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
813
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
814
    - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
815
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
816
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
817
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
818
    - Your programming IDE is your friend, find the type or function declaration to find comments
819
      associated with it.
820
821
 Q: What is this library called?
822
 Q: Which version should I get?
823
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
824
 >> See https://www.dearimgui.com/faq for details.
825
826
 Q&A: Integration
827
 ================
828
829
 Q: How to get started?
830
 A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
831
832
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
833
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
834
 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
835
836
 Q. How can I enable keyboard controls?
837
 Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
838
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
839
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
840
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
841
 >> See https://www.dearimgui.com/faq
842
843
 Q&A: Usage
844
 ----------
845
846
 Q: About the ID Stack system..
847
   - Why is my widget not reacting when I click on it?
848
   - How can I have widgets with an empty label?
849
   - How can I have multiple widgets with the same label?
850
   - How can I have multiple windows with the same label?
851
 Q: How can I display an image? What is ImTextureID, how does it work?
852
 Q: How can I use my own math types instead of ImVec2/ImVec4?
853
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
854
 Q: How can I display custom shapes? (using low-level ImDrawList API)
855
 >> See https://www.dearimgui.com/faq
856
857
 Q&A: Fonts, Text
858
 ================
859
860
 Q: How should I handle DPI in my application?
861
 Q: How can I load a different font than the default?
862
 Q: How can I easily use icons in my application?
863
 Q: How can I load multiple fonts?
864
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
865
 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
866
867
 Q&A: Concerns
868
 =============
869
870
 Q: Who uses Dear ImGui?
871
 Q: Can you create elaborate/serious tools with Dear ImGui?
872
 Q: Can you reskin the look of Dear ImGui?
873
 Q: Why using C++ (as opposed to C)?
874
 >> See https://www.dearimgui.com/faq
875
876
 Q&A: Community
877
 ==============
878
879
 Q: How can I help?
880
 A: - Businesses: please reach out to "contact AT dearimgui.com" if you work in a place using Dear ImGui!
881
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
882
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people working on this project.
883
    - Individuals: you can support continued development via PayPal donations. See README.
884
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, read docs/TODO.txt
885
      and see how you want to help and can help!
886
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
887
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
888
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
889
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
890
891
*/
892
893
//-------------------------------------------------------------------------
894
// [SECTION] INCLUDES
895
//-------------------------------------------------------------------------
896
897
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
898
#define _CRT_SECURE_NO_WARNINGS
899
#endif
900
901
#ifndef IMGUI_DEFINE_MATH_OPERATORS
902
#define IMGUI_DEFINE_MATH_OPERATORS
903
#endif
904
905
#include "imgui.h"
906
#ifndef IMGUI_DISABLE
907
#include "imgui_internal.h"
908
909
// System includes
910
#include <stdio.h>      // vsnprintf, sscanf, printf
911
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
912
#include <stddef.h>     // intptr_t
913
#else
914
#include <stdint.h>     // intptr_t
915
#endif
916
917
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
918
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
919
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
920
#endif
921
922
// [Windows] OS specific includes (optional)
923
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
924
#define IMGUI_DISABLE_WIN32_FUNCTIONS
925
#endif
926
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
927
#ifndef WIN32_LEAN_AND_MEAN
928
#define WIN32_LEAN_AND_MEAN
929
#endif
930
#ifndef NOMINMAX
931
#define NOMINMAX
932
#endif
933
#ifndef __MINGW32__
934
#include <Windows.h>        // _wfopen, OpenClipboard
935
#else
936
#include <windows.h>
937
#endif
938
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
939
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
940
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
941
#endif
942
#endif
943
944
// [Apple] OS specific includes
945
#if defined(__APPLE__)
946
#include <TargetConditionals.h>
947
#endif
948
949
// Visual Studio warnings
950
#ifdef _MSC_VER
951
#pragma warning (disable: 4127)             // condition expression is constant
952
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
953
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
954
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
955
#endif
956
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
957
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
958
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
959
#endif
960
961
// Clang/GCC warnings with -Weverything
962
#if defined(__clang__)
963
#if __has_warning("-Wunknown-warning-option")
964
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
965
#endif
966
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
967
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
968
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
969
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
970
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
971
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
972
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
973
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
974
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
975
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
976
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
977
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
978
#elif defined(__GNUC__)
979
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
980
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
981
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
982
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
983
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
984
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
985
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
986
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
987
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
988
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
989
#endif
990
991
// Debug options
992
82.6k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
993
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
994
995
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
996
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
997
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
998
999
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1000
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1001
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
1002
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1003
1004
// Docking
1005
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1006
static const float DOCKING_SPLITTER_SIZE                    = 2.0f;
1007
1008
//-------------------------------------------------------------------------
1009
// [SECTION] FORWARD DECLARATIONS
1010
//-------------------------------------------------------------------------
1011
1012
static void             SetCurrentWindow(ImGuiWindow* window);
1013
static void             FindHoveredWindow();
1014
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1015
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1016
1017
static void             AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
1018
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1019
1020
// Settings
1021
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1022
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1023
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1024
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1025
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1026
1027
// Platform Dependents default implementation for IO functions
1028
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1029
static void             SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1030
static void             SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1031
1032
namespace ImGui
1033
{
1034
// Navigation
1035
static void             NavUpdate();
1036
static void             NavUpdateWindowing();
1037
static void             NavUpdateWindowingOverlay();
1038
static void             NavUpdateCancelRequest();
1039
static void             NavUpdateCreateMoveRequest();
1040
static void             NavUpdateCreateTabbingRequest();
1041
static float            NavUpdatePageUpPageDown();
1042
static inline void      NavUpdateAnyRequestFlag();
1043
static void             NavUpdateCreateWrappingRequest();
1044
static void             NavEndFrame();
1045
static bool             NavScoreItem(ImGuiNavItemData* result);
1046
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1047
static void             NavProcessItem();
1048
static void             NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1049
static ImVec2           NavCalcPreferredRefPos();
1050
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1051
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1052
static void             NavRestoreLayer(ImGuiNavLayer layer);
1053
static void             NavRestoreHighlightAfterMove();
1054
static int              FindWindowFocusIndex(ImGuiWindow* window);
1055
1056
// Error Checking and Debug Tools
1057
static void             ErrorCheckNewFrameSanityChecks();
1058
static void             ErrorCheckEndFrameSanityChecks();
1059
static void             UpdateDebugToolItemPicker();
1060
static void             UpdateDebugToolStackQueries();
1061
1062
// Inputs
1063
static void             UpdateKeyboardInputs();
1064
static void             UpdateMouseInputs();
1065
static void             UpdateMouseWheel();
1066
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1067
1068
// Misc
1069
static void             UpdateSettings();
1070
static bool             UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1071
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1072
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1073
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1074
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1075
static void             RenderDimmedBackgrounds();
1076
1077
// Viewports
1078
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1079
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1080
static void             DestroyViewport(ImGuiViewportP* viewport);
1081
static void             UpdateViewportsNewFrame();
1082
static void             UpdateViewportsEndFrame();
1083
static void             WindowSelectViewport(ImGuiWindow* window);
1084
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1085
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1086
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1087
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1088
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1089
static int              FindPlatformMonitorForRect(const ImRect& r);
1090
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1091
1092
}
1093
1094
//-----------------------------------------------------------------------------
1095
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1096
//-----------------------------------------------------------------------------
1097
1098
// DLL users:
1099
// - Heaps and globals are not shared across DLL boundaries!
1100
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1101
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1102
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1103
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1104
1105
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1106
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1107
//   Change to a different context by calling ImGui::SetCurrentContext().
1108
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1109
//   If you want thread-safety to allow N threads to access N different contexts:
1110
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1111
//         struct ImGuiContext;
1112
//         extern thread_local ImGuiContext* MyImGuiTLS;
1113
//         #define GImGui MyImGuiTLS
1114
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1115
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1116
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1117
// - DLL users: read comments above.
1118
#ifndef GImGui
1119
ImGuiContext*   GImGui = NULL;
1120
#endif
1121
1122
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1123
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1124
// - DLL users: read comments above.
1125
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1126
1.25k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1127
1.20k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1128
#else
1129
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1130
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1131
#endif
1132
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1133
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1134
static void*                GImAllocatorUserData = NULL;
1135
1136
//-----------------------------------------------------------------------------
1137
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1138
//-----------------------------------------------------------------------------
1139
1140
ImGuiStyle::ImGuiStyle()
1141
1
{
1142
1
    Alpha                   = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1143
1
    DisabledAlpha           = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1144
1
    WindowPadding           = ImVec2(8,8);      // Padding within a window
1145
1
    WindowRounding          = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1146
1
    WindowBorderSize        = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1147
1
    WindowMinSize           = ImVec2(32,32);    // Minimum window size
1148
1
    WindowTitleAlign        = ImVec2(0.0f,0.5f);// Alignment for title bar text
1149
1
    WindowMenuButtonPosition= ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1150
1
    ChildRounding           = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1151
1
    ChildBorderSize         = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1152
1
    PopupRounding           = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1153
1
    PopupBorderSize         = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1154
1
    FramePadding            = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1155
1
    FrameRounding           = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1156
1
    FrameBorderSize         = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1157
1
    ItemSpacing             = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1158
1
    ItemInnerSpacing        = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1159
1
    CellPadding             = ImVec2(4,2);      // Padding within a table cell
1160
1
    TouchExtraPadding       = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1161
1
    IndentSpacing           = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1162
1
    ColumnsMinSpacing       = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1163
1
    ScrollbarSize           = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1164
1
    ScrollbarRounding       = 9.0f;             // Radius of grab corners rounding for scrollbar
1165
1
    GrabMinSize             = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1166
1
    GrabRounding            = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1167
1
    LogSliderDeadzone       = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1168
1
    TabRounding             = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1169
1
    TabBorderSize           = 0.0f;             // Thickness of border around tabs.
1170
1
    TabMinWidthForCloseButton = 0.0f;           // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1171
1
    ColorButtonPosition     = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1172
1
    ButtonTextAlign         = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1173
1
    SelectableTextAlign     = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1174
1
    SeparatorTextBorderSize = 3.0f;             // Thickkness of border in SeparatorText()
1175
1
    SeparatorTextAlign      = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1176
1
    SeparatorTextPadding    = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1177
1
    DisplayWindowPadding    = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1178
1
    DisplaySafeAreaPadding  = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1179
1
    MouseCursorScale        = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1180
1
    AntiAliasedLines        = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1181
1
    AntiAliasedLinesUseTex  = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1182
1
    AntiAliasedFill         = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1183
1
    CurveTessellationTol    = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1184
1
    CircleTessellationMaxError = 0.30f;         // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1185
1186
    // Default theme
1187
1
    ImGui::StyleColorsDark(this);
1188
1
}
1189
1190
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1191
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1192
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1193
0
{
1194
0
    WindowPadding = ImFloor(WindowPadding * scale_factor);
1195
0
    WindowRounding = ImFloor(WindowRounding * scale_factor);
1196
0
    WindowMinSize = ImFloor(WindowMinSize * scale_factor);
1197
0
    ChildRounding = ImFloor(ChildRounding * scale_factor);
1198
0
    PopupRounding = ImFloor(PopupRounding * scale_factor);
1199
0
    FramePadding = ImFloor(FramePadding * scale_factor);
1200
0
    FrameRounding = ImFloor(FrameRounding * scale_factor);
1201
0
    ItemSpacing = ImFloor(ItemSpacing * scale_factor);
1202
0
    ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
1203
0
    CellPadding = ImFloor(CellPadding * scale_factor);
1204
0
    TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
1205
0
    IndentSpacing = ImFloor(IndentSpacing * scale_factor);
1206
0
    ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
1207
0
    ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
1208
0
    ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
1209
0
    GrabMinSize = ImFloor(GrabMinSize * scale_factor);
1210
0
    GrabRounding = ImFloor(GrabRounding * scale_factor);
1211
0
    LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor);
1212
0
    TabRounding = ImFloor(TabRounding * scale_factor);
1213
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1214
0
    SeparatorTextPadding = ImFloor(SeparatorTextPadding * scale_factor);
1215
0
    DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
1216
0
    DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
1217
0
    MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
1218
0
}
1219
1220
ImGuiIO::ImGuiIO()
1221
1
{
1222
    // Most fields are initialized with zero
1223
1
    memset(this, 0, sizeof(*this));
1224
1
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1225
1226
    // Settings
1227
1
    ConfigFlags = ImGuiConfigFlags_None;
1228
1
    BackendFlags = ImGuiBackendFlags_None;
1229
1
    DisplaySize = ImVec2(-1.0f, -1.0f);
1230
1
    DeltaTime = 1.0f / 60.0f;
1231
1
    IniSavingRate = 5.0f;
1232
1
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1233
1
    LogFilename = "imgui_log.txt";
1234
1
    MouseDoubleClickTime = 0.30f;
1235
1
    MouseDoubleClickMaxDist = 6.0f;
1236
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1237
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1238
        KeyMap[i] = -1;
1239
#endif
1240
1
    KeyRepeatDelay = 0.275f;
1241
1
    KeyRepeatRate = 0.050f;
1242
1
    HoverDelayNormal = 0.30f;
1243
1
    HoverDelayShort = 0.10f;
1244
1
    UserData = NULL;
1245
1246
1
    Fonts = NULL;
1247
1
    FontGlobalScale = 1.0f;
1248
1
    FontDefault = NULL;
1249
1
    FontAllowUserScaling = false;
1250
1
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1251
1252
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1253
1
    ConfigDockingNoSplit = false;
1254
1
    ConfigDockingWithShift = false;
1255
1
    ConfigDockingAlwaysTabBar = false;
1256
1
    ConfigDockingTransparentPayload = false;
1257
1258
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1259
1
    ConfigViewportsNoAutoMerge = false;
1260
1
    ConfigViewportsNoTaskBarIcon = false;
1261
1
    ConfigViewportsNoDecoration = true;
1262
1
    ConfigViewportsNoDefaultParent = false;
1263
1264
    // Miscellaneous options
1265
1
    MouseDrawCursor = false;
1266
#ifdef __APPLE__
1267
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1268
#else
1269
1
    ConfigMacOSXBehaviors = false;
1270
1
#endif
1271
1
    ConfigInputTrickleEventQueue = true;
1272
1
    ConfigInputTextCursorBlink = true;
1273
1
    ConfigInputTextEnterKeepActive = false;
1274
1
    ConfigDragClickToInputText = false;
1275
1
    ConfigWindowsResizeFromEdges = true;
1276
1
    ConfigWindowsMoveFromTitleBarOnly = false;
1277
1
    ConfigMemoryCompactTimer = 60.0f;
1278
1
    ConfigDebugBeginReturnValueOnce = false;
1279
1
    ConfigDebugBeginReturnValueLoop = false;
1280
1281
    // Platform Functions
1282
    // Note: Initialize() will setup default clipboard/ime handlers.
1283
1
    BackendPlatformName = BackendRendererName = NULL;
1284
1
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1285
1286
    // Input (NB: we already have memset zero the entire structure!)
1287
1
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1288
1
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1289
1
    MouseSource = ImGuiMouseSource_Mouse;
1290
1
    MouseDragThreshold = 6.0f;
1291
6
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1292
141
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1293
1
    AppAcceptingEvents = true;
1294
1
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1295
1
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1296
1
}
1297
1298
// Pass in translated ASCII characters for text input.
1299
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1300
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1301
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1302
void ImGuiIO::AddInputCharacter(unsigned int c)
1303
5.29k
{
1304
5.29k
    IM_ASSERT(Ctx != NULL);
1305
5.29k
    ImGuiContext& g = *Ctx;
1306
5.29k
    if (c == 0 || !AppAcceptingEvents)
1307
2.03k
        return;
1308
1309
3.26k
    ImGuiInputEvent e;
1310
3.26k
    e.Type = ImGuiInputEventType_Text;
1311
3.26k
    e.Source = ImGuiInputSource_Keyboard;
1312
3.26k
    e.EventId = g.InputEventsNextEventId++;
1313
3.26k
    e.Text.Char = c;
1314
3.26k
    g.InputEventsQueue.push_back(e);
1315
3.26k
}
1316
1317
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1318
// we should save the high surrogate.
1319
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1320
2.82k
{
1321
2.82k
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1322
312
        return;
1323
1324
2.50k
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1325
1.11k
    {
1326
1.11k
        if (InputQueueSurrogate != 0)
1327
375
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1328
1.11k
        InputQueueSurrogate = c;
1329
1.11k
        return;
1330
1.11k
    }
1331
1332
1.39k
    ImWchar cp = c;
1333
1.39k
    if (InputQueueSurrogate != 0)
1334
682
    {
1335
682
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1336
225
        {
1337
225
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1338
225
        }
1339
457
        else
1340
457
        {
1341
457
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1342
457
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1343
#else
1344
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1345
#endif
1346
457
        }
1347
1348
682
        InputQueueSurrogate = 0;
1349
682
    }
1350
1.39k
    AddInputCharacter((unsigned)cp);
1351
1.39k
}
1352
1353
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1354
68
{
1355
68
    if (!AppAcceptingEvents)
1356
0
        return;
1357
68
    while (*utf8_chars != 0)
1358
0
    {
1359
0
        unsigned int c = 0;
1360
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1361
0
        AddInputCharacter(c);
1362
0
    }
1363
68
}
1364
1365
// FIXME: Perhaps we could clear queued events as well?
1366
void ImGuiIO::ClearInputCharacters()
1367
7.05k
{
1368
7.05k
    InputQueueCharacters.resize(0);
1369
7.05k
}
1370
1371
// FIXME: Perhaps we could clear queued events as well?
1372
void ImGuiIO::ClearInputKeys()
1373
7.28k
{
1374
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1375
    memset(KeysDown, 0, sizeof(KeysDown));
1376
#endif
1377
1.02M
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1378
1.01M
    {
1379
1.01M
        KeysData[n].Down             = false;
1380
1.01M
        KeysData[n].DownDuration     = -1.0f;
1381
1.01M
        KeysData[n].DownDurationPrev = -1.0f;
1382
1.01M
    }
1383
7.28k
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1384
7.28k
    KeyMods = ImGuiMod_None;
1385
7.28k
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1386
43.6k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1387
36.4k
    {
1388
36.4k
        MouseDown[n] = false;
1389
36.4k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1390
36.4k
    }
1391
7.28k
    MouseWheel = MouseWheelH = 0.0f;
1392
7.28k
}
1393
1394
static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1395
7.16k
{
1396
7.16k
    ImGuiContext& g = *ctx;
1397
12.2k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1398
6.77k
    {
1399
6.77k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1400
6.77k
        if (e->Type != type)
1401
3.98k
            continue;
1402
2.79k
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1403
442
            continue;
1404
2.35k
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1405
633
            continue;
1406
1.71k
        return e;
1407
2.35k
    }
1408
5.44k
    return NULL;
1409
7.16k
}
1410
1411
// Queue a new key down/up event.
1412
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1413
// - bool down:          Is the key down? use false to signify a key release.
1414
// - float analog_value: 0.0f..1.0f
1415
// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1416
// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULLFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1417
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1418
2.13k
{
1419
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1420
2.13k
    IM_ASSERT(Ctx != NULL);
1421
2.13k
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1422
0
        return;
1423
2.13k
    ImGuiContext& g = *Ctx;
1424
2.13k
    IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1425
2.13k
    IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1426
2.13k
    IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1427
1428
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1429
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1430
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1431
    if (BackendUsingLegacyKeyArrays == -1)
1432
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1433
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1434
    BackendUsingLegacyKeyArrays = 0;
1435
#endif
1436
2.13k
    if (ImGui::IsGamepadKey(key))
1437
25
        BackendUsingLegacyNavInputArray = false;
1438
1439
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1440
2.13k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1441
2.13k
    const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1442
2.13k
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1443
2.13k
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1444
2.13k
    if (latest_key_down == down && latest_key_analog == analog_value)
1445
461
        return;
1446
1447
    // Add event
1448
1.66k
    ImGuiInputEvent e;
1449
1.66k
    e.Type = ImGuiInputEventType_Key;
1450
1.66k
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1451
1.66k
    e.EventId = g.InputEventsNextEventId++;
1452
1.66k
    e.Key.Key = key;
1453
1.66k
    e.Key.Down = down;
1454
1.66k
    e.Key.AnalogValue = analog_value;
1455
1.66k
    g.InputEventsQueue.push_back(e);
1456
1.66k
}
1457
1458
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1459
525
{
1460
525
    if (!AppAcceptingEvents)
1461
0
        return;
1462
525
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1463
525
}
1464
1465
// [Optional] Call after AddKeyEvent().
1466
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1467
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1468
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1469
0
{
1470
0
    if (key == ImGuiKey_None)
1471
0
        return;
1472
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1473
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1474
0
    IM_UNUSED(native_keycode);  // Yet unused
1475
0
    IM_UNUSED(native_scancode); // Yet unused
1476
1477
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1478
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1479
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1480
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1481
        return;
1482
    KeyMap[legacy_key] = key;
1483
    KeyMap[key] = legacy_key;
1484
#else
1485
0
    IM_UNUSED(key);
1486
0
    IM_UNUSED(native_legacy_index);
1487
0
#endif
1488
0
}
1489
1490
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1491
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1492
0
{
1493
0
    AppAcceptingEvents = accepting_events;
1494
0
}
1495
1496
// Queue a mouse move event
1497
void ImGuiIO::AddMousePosEvent(float x, float y)
1498
2.23k
{
1499
2.23k
    IM_ASSERT(Ctx != NULL);
1500
2.23k
    ImGuiContext& g = *Ctx;
1501
2.23k
    if (!AppAcceptingEvents)
1502
0
        return;
1503
1504
    // Apply same flooring as UpdateMouseInputs()
1505
2.23k
    ImVec2 pos((x > -FLT_MAX) ? ImFloorSigned(x) : x, (y > -FLT_MAX) ? ImFloorSigned(y) : y);
1506
1507
    // Filter duplicate
1508
2.23k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1509
2.23k
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1510
2.23k
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1511
459
        return;
1512
1513
1.77k
    ImGuiInputEvent e;
1514
1.77k
    e.Type = ImGuiInputEventType_MousePos;
1515
1.77k
    e.Source = ImGuiInputSource_Mouse;
1516
1.77k
    e.EventId = g.InputEventsNextEventId++;
1517
1.77k
    e.MousePos.PosX = pos.x;
1518
1.77k
    e.MousePos.PosY = pos.y;
1519
1.77k
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1520
1.77k
    g.InputEventsQueue.push_back(e);
1521
1.77k
}
1522
1523
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1524
2.36k
{
1525
2.36k
    IM_ASSERT(Ctx != NULL);
1526
2.36k
    ImGuiContext& g = *Ctx;
1527
2.36k
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1528
2.36k
    if (!AppAcceptingEvents)
1529
0
        return;
1530
1531
    // Filter duplicate
1532
2.36k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1533
2.36k
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1534
2.36k
    if (latest_button_down == down)
1535
503
        return;
1536
1537
1.86k
    ImGuiInputEvent e;
1538
1.86k
    e.Type = ImGuiInputEventType_MouseButton;
1539
1.86k
    e.Source = ImGuiInputSource_Mouse;
1540
1.86k
    e.EventId = g.InputEventsNextEventId++;
1541
1.86k
    e.MouseButton.Button = mouse_button;
1542
1.86k
    e.MouseButton.Down = down;
1543
1.86k
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1544
1.86k
    g.InputEventsQueue.push_back(e);
1545
1.86k
}
1546
1547
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1548
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1549
1.48k
{
1550
1.48k
    IM_ASSERT(Ctx != NULL);
1551
1.48k
    ImGuiContext& g = *Ctx;
1552
1553
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1554
1.48k
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1555
28
        return;
1556
1557
1.45k
    ImGuiInputEvent e;
1558
1.45k
    e.Type = ImGuiInputEventType_MouseWheel;
1559
1.45k
    e.Source = ImGuiInputSource_Mouse;
1560
1.45k
    e.EventId = g.InputEventsNextEventId++;
1561
1.45k
    e.MouseWheel.WheelX = wheel_x;
1562
1.45k
    e.MouseWheel.WheelY = wheel_y;
1563
1.45k
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1564
1.45k
    g.InputEventsQueue.push_back(e);
1565
1.45k
}
1566
1567
// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1568
// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1569
void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1570
0
{
1571
0
    IM_ASSERT(Ctx != NULL);
1572
0
    ImGuiContext& g = *Ctx;
1573
0
    g.InputEventsNextMouseSource = source;
1574
0
}
1575
1576
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1577
0
{
1578
0
    IM_ASSERT(Ctx != NULL);
1579
0
    ImGuiContext& g = *Ctx;
1580
    //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1581
0
    if (!AppAcceptingEvents)
1582
0
        return;
1583
1584
    // Filter duplicate
1585
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1586
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1587
0
    if (latest_viewport_id == viewport_id)
1588
0
        return;
1589
1590
0
    ImGuiInputEvent e;
1591
0
    e.Type = ImGuiInputEventType_MouseViewport;
1592
0
    e.Source = ImGuiInputSource_Mouse;
1593
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1594
0
    g.InputEventsQueue.push_back(e);
1595
0
}
1596
1597
void ImGuiIO::AddFocusEvent(bool focused)
1598
441
{
1599
441
    IM_ASSERT(Ctx != NULL);
1600
441
    ImGuiContext& g = *Ctx;
1601
1602
    // Filter duplicate
1603
441
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1604
441
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1605
441
    if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1606
138
        return;
1607
1608
303
    ImGuiInputEvent e;
1609
303
    e.Type = ImGuiInputEventType_Focus;
1610
303
    e.EventId = g.InputEventsNextEventId++;
1611
303
    e.AppFocused.Focused = focused;
1612
303
    g.InputEventsQueue.push_back(e);
1613
303
}
1614
1615
//-----------------------------------------------------------------------------
1616
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1617
//-----------------------------------------------------------------------------
1618
1619
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1620
0
{
1621
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1622
0
    ImVec2 p_last = p1;
1623
0
    ImVec2 p_closest;
1624
0
    float p_closest_dist2 = FLT_MAX;
1625
0
    float t_step = 1.0f / (float)num_segments;
1626
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1627
0
    {
1628
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1629
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1630
0
        float dist2 = ImLengthSqr(p - p_line);
1631
0
        if (dist2 < p_closest_dist2)
1632
0
        {
1633
0
            p_closest = p_line;
1634
0
            p_closest_dist2 = dist2;
1635
0
        }
1636
0
        p_last = p_current;
1637
0
    }
1638
0
    return p_closest;
1639
0
}
1640
1641
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1642
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1643
0
{
1644
0
    float dx = x4 - x1;
1645
0
    float dy = y4 - y1;
1646
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1647
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1648
0
    d2 = (d2 >= 0) ? d2 : -d2;
1649
0
    d3 = (d3 >= 0) ? d3 : -d3;
1650
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1651
0
    {
1652
0
        ImVec2 p_current(x4, y4);
1653
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1654
0
        float dist2 = ImLengthSqr(p - p_line);
1655
0
        if (dist2 < p_closest_dist2)
1656
0
        {
1657
0
            p_closest = p_line;
1658
0
            p_closest_dist2 = dist2;
1659
0
        }
1660
0
        p_last = p_current;
1661
0
    }
1662
0
    else if (level < 10)
1663
0
    {
1664
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1665
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1666
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1667
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1668
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1669
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1670
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1671
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1672
0
    }
1673
0
}
1674
1675
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1676
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1677
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1678
0
{
1679
0
    IM_ASSERT(tess_tol > 0.0f);
1680
0
    ImVec2 p_last = p1;
1681
0
    ImVec2 p_closest;
1682
0
    float p_closest_dist2 = FLT_MAX;
1683
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1684
0
    return p_closest;
1685
0
}
1686
1687
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1688
0
{
1689
0
    ImVec2 ap = p - a;
1690
0
    ImVec2 ab_dir = b - a;
1691
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1692
0
    if (dot < 0.0f)
1693
0
        return a;
1694
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1695
0
    if (dot > ab_len_sqr)
1696
0
        return b;
1697
0
    return a + ab_dir * dot / ab_len_sqr;
1698
0
}
1699
1700
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1701
0
{
1702
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1703
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1704
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1705
0
    return ((b1 == b2) && (b2 == b3));
1706
0
}
1707
1708
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1709
0
{
1710
0
    ImVec2 v0 = b - a;
1711
0
    ImVec2 v1 = c - a;
1712
0
    ImVec2 v2 = p - a;
1713
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1714
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1715
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1716
0
    out_u = 1.0f - out_v - out_w;
1717
0
}
1718
1719
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1720
0
{
1721
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1722
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1723
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1724
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1725
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1726
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1727
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1728
0
    if (m == dist2_ab)
1729
0
        return proj_ab;
1730
0
    if (m == dist2_bc)
1731
0
        return proj_bc;
1732
0
    return proj_ca;
1733
0
}
1734
1735
//-----------------------------------------------------------------------------
1736
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1737
//-----------------------------------------------------------------------------
1738
1739
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1740
int ImStricmp(const char* str1, const char* str2)
1741
0
{
1742
0
    int d;
1743
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1744
0
    return d;
1745
0
}
1746
1747
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1748
0
{
1749
0
    int d = 0;
1750
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1751
0
    return d;
1752
0
}
1753
1754
void ImStrncpy(char* dst, const char* src, size_t count)
1755
18
{
1756
18
    if (count < 1)
1757
0
        return;
1758
18
    if (count > 1)
1759
18
        strncpy(dst, src, count - 1);
1760
18
    dst[count - 1] = 0;
1761
18
}
1762
1763
char* ImStrdup(const char* str)
1764
3
{
1765
3
    size_t len = strlen(str);
1766
3
    void* buf = IM_ALLOC(len + 1);
1767
3
    return (char*)memcpy(buf, (const void*)str, len + 1);
1768
3
}
1769
1770
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1771
0
{
1772
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1773
0
    size_t src_size = strlen(src) + 1;
1774
0
    if (dst_buf_size < src_size)
1775
0
    {
1776
0
        IM_FREE(dst);
1777
0
        dst = (char*)IM_ALLOC(src_size);
1778
0
        if (p_dst_size)
1779
0
            *p_dst_size = src_size;
1780
0
    }
1781
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1782
0
}
1783
1784
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1785
0
{
1786
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1787
0
    return p;
1788
0
}
1789
1790
int ImStrlenW(const ImWchar* str)
1791
0
{
1792
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1793
0
    int n = 0;
1794
0
    while (*str++) n++;
1795
0
    return n;
1796
0
}
1797
1798
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1799
const char* ImStreolRange(const char* str, const char* str_end)
1800
0
{
1801
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
1802
0
    return p ? p : str_end;
1803
0
}
1804
1805
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1806
0
{
1807
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1808
0
        buf_mid_line--;
1809
0
    return buf_mid_line;
1810
0
}
1811
1812
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1813
0
{
1814
0
    if (!needle_end)
1815
0
        needle_end = needle + strlen(needle);
1816
1817
0
    const char un0 = (char)ImToUpper(*needle);
1818
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1819
0
    {
1820
0
        if (ImToUpper(*haystack) == un0)
1821
0
        {
1822
0
            const char* b = needle + 1;
1823
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
1824
0
                if (ImToUpper(*a) != ImToUpper(*b))
1825
0
                    break;
1826
0
            if (b == needle_end)
1827
0
                return haystack;
1828
0
        }
1829
0
        haystack++;
1830
0
    }
1831
0
    return NULL;
1832
0
}
1833
1834
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
1835
void ImStrTrimBlanks(char* buf)
1836
0
{
1837
0
    char* p = buf;
1838
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
1839
0
        p++;
1840
0
    char* p_start = p;
1841
0
    while (*p != 0)                         // Find end of string
1842
0
        p++;
1843
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
1844
0
        p--;
1845
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
1846
0
        memmove(buf, p_start, p - p_start);
1847
0
    buf[p - p_start] = 0;                   // Zero terminate
1848
0
}
1849
1850
const char* ImStrSkipBlank(const char* str)
1851
0
{
1852
0
    while (str[0] == ' ' || str[0] == '\t')
1853
0
        str++;
1854
0
    return str;
1855
0
}
1856
1857
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1858
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
1859
// B) When buf==NULL vsnprintf() will return the output size.
1860
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1861
1862
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1863
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1864
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1865
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1866
#ifdef IMGUI_USE_STB_SPRINTF
1867
#define STB_SPRINTF_IMPLEMENTATION
1868
#ifdef IMGUI_STB_SPRINTF_FILENAME
1869
#include IMGUI_STB_SPRINTF_FILENAME
1870
#else
1871
#include "stb_sprintf.h"
1872
#endif
1873
#endif
1874
1875
#if defined(_MSC_VER) && !defined(vsnprintf)
1876
#define vsnprintf _vsnprintf
1877
#endif
1878
1879
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1880
1
{
1881
1
    va_list args;
1882
1
    va_start(args, fmt);
1883
#ifdef IMGUI_USE_STB_SPRINTF
1884
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1885
#else
1886
1
    int w = vsnprintf(buf, buf_size, fmt, args);
1887
1
#endif
1888
1
    va_end(args);
1889
1
    if (buf == NULL)
1890
0
        return w;
1891
1
    if (w == -1 || w >= (int)buf_size)
1892
0
        w = (int)buf_size - 1;
1893
1
    buf[w] = 0;
1894
1
    return w;
1895
1
}
1896
1897
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1898
35.9k
{
1899
#ifdef IMGUI_USE_STB_SPRINTF
1900
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1901
#else
1902
35.9k
    int w = vsnprintf(buf, buf_size, fmt, args);
1903
35.9k
#endif
1904
35.9k
    if (buf == NULL)
1905
0
        return w;
1906
35.9k
    if (w == -1 || w >= (int)buf_size)
1907
0
        w = (int)buf_size - 1;
1908
35.9k
    buf[w] = 0;
1909
35.9k
    return w;
1910
35.9k
}
1911
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1912
1913
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
1914
35.9k
{
1915
35.9k
    ImGuiContext& g = *GImGui;
1916
35.9k
    va_list args;
1917
35.9k
    va_start(args, fmt);
1918
35.9k
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
1919
0
    {
1920
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
1921
0
        *out_buf = buf;
1922
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
1923
0
    }
1924
35.9k
    else
1925
35.9k
    {
1926
35.9k
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
1927
35.9k
        *out_buf = g.TempBuffer.Data;
1928
35.9k
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1929
35.9k
    }
1930
35.9k
    va_end(args);
1931
35.9k
}
1932
1933
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
1934
0
{
1935
0
    ImGuiContext& g = *GImGui;
1936
0
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
1937
0
    {
1938
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
1939
0
        *out_buf = buf;
1940
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
1941
0
    }
1942
0
    else
1943
0
    {
1944
0
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
1945
0
        *out_buf = g.TempBuffer.Data;
1946
0
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1947
0
    }
1948
0
}
1949
1950
// CRC32 needs a 1KB lookup table (not cache friendly)
1951
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
1952
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
1953
static const ImU32 GCrc32LookupTable[256] =
1954
{
1955
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
1956
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
1957
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
1958
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
1959
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
1960
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
1961
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
1962
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
1963
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
1964
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
1965
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
1966
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
1967
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
1968
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
1969
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
1970
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
1971
};
1972
1973
// Known size hash
1974
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
1975
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1976
ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
1977
35.9k
{
1978
35.9k
    ImU32 crc = ~seed;
1979
35.9k
    const unsigned char* data = (const unsigned char*)data_p;
1980
35.9k
    const ImU32* crc32_lut = GCrc32LookupTable;
1981
179k
    while (data_size-- != 0)
1982
143k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
1983
35.9k
    return ~crc;
1984
35.9k
}
1985
1986
// Zero-terminated string hash, with support for ### to reset back to seed value
1987
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
1988
// Because this syntax is rarely used we are optimizing for the common case.
1989
// - If we reach ### in the string we discard the hash so far and reset to the seed.
1990
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
1991
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1992
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
1993
395k
{
1994
395k
    seed = ~seed;
1995
395k
    ImU32 crc = seed;
1996
395k
    const unsigned char* data = (const unsigned char*)data_p;
1997
395k
    const ImU32* crc32_lut = GCrc32LookupTable;
1998
395k
    if (data_size != 0)
1999
0
    {
2000
0
        while (data_size-- != 0)
2001
0
        {
2002
0
            unsigned char c = *data++;
2003
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2004
0
                crc = seed;
2005
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2006
0
        }
2007
0
    }
2008
395k
    else
2009
395k
    {
2010
5.32M
        while (unsigned char c = *data++)
2011
4.92M
        {
2012
4.92M
            if (c == '#' && data[0] == '#' && data[1] == '#')
2013
35.9k
                crc = seed;
2014
4.92M
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2015
4.92M
        }
2016
395k
    }
2017
395k
    return ~crc;
2018
395k
}
2019
2020
//-----------------------------------------------------------------------------
2021
// [SECTION] MISC HELPERS/UTILITIES (File functions)
2022
//-----------------------------------------------------------------------------
2023
2024
// Default file functions
2025
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2026
2027
ImFileHandle ImFileOpen(const char* filename, const char* mode)
2028
0
{
2029
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2030
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2031
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2032
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2033
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2034
    ImVector<wchar_t> buf;
2035
    buf.resize(filename_wsize + mode_wsize);
2036
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
2037
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
2038
    return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
2039
#else
2040
0
    return fopen(filename, mode);
2041
0
#endif
2042
0
}
2043
2044
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2045
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
2046
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2047
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
2048
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
2049
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2050
2051
// Helper: Load file content into memory
2052
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2053
// This can't really be used with "rt" because fseek size won't match read size.
2054
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2055
0
{
2056
0
    IM_ASSERT(filename && mode);
2057
0
    if (out_file_size)
2058
0
        *out_file_size = 0;
2059
2060
0
    ImFileHandle f;
2061
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2062
0
        return NULL;
2063
2064
0
    size_t file_size = (size_t)ImFileGetSize(f);
2065
0
    if (file_size == (size_t)-1)
2066
0
    {
2067
0
        ImFileClose(f);
2068
0
        return NULL;
2069
0
    }
2070
2071
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2072
0
    if (file_data == NULL)
2073
0
    {
2074
0
        ImFileClose(f);
2075
0
        return NULL;
2076
0
    }
2077
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2078
0
    {
2079
0
        ImFileClose(f);
2080
0
        IM_FREE(file_data);
2081
0
        return NULL;
2082
0
    }
2083
0
    if (padding_bytes > 0)
2084
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2085
2086
0
    ImFileClose(f);
2087
0
    if (out_file_size)
2088
0
        *out_file_size = file_size;
2089
2090
0
    return file_data;
2091
0
}
2092
2093
//-----------------------------------------------------------------------------
2094
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2095
//-----------------------------------------------------------------------------
2096
2097
IM_MSVC_RUNTIME_CHECKS_OFF
2098
2099
// Convert UTF-8 to 32-bit character, process single character input.
2100
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2101
// We handle UTF-8 decoding error by skipping forward.
2102
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2103
12.3M
{
2104
12.3M
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2105
12.3M
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2106
12.3M
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2107
12.3M
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2108
12.3M
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2109
12.3M
    int len = lengths[*(const unsigned char*)in_text >> 3];
2110
12.3M
    int wanted = len + (len ? 0 : 1);
2111
2112
12.3M
    if (in_text_end == NULL)
2113
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2114
2115
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2116
    // so it is fast even with excessive branching.
2117
12.3M
    unsigned char s[4];
2118
12.3M
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2119
12.3M
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2120
12.3M
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2121
12.3M
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2122
2123
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2124
12.3M
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2125
12.3M
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2126
12.3M
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2127
12.3M
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2128
12.3M
    *out_char >>= shiftc[len];
2129
2130
    // Accumulate the various error conditions.
2131
12.3M
    int e = 0;
2132
12.3M
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2133
12.3M
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2134
12.3M
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2135
12.3M
    e |= (s[1] & 0xc0) >> 2;
2136
12.3M
    e |= (s[2] & 0xc0) >> 4;
2137
12.3M
    e |= (s[3]       ) >> 6;
2138
12.3M
    e ^= 0x2a; // top two bits of each tail byte correct?
2139
12.3M
    e >>= shifte[len];
2140
2141
12.3M
    if (e)
2142
557k
    {
2143
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2144
        // One byte is consumed in case of invalid first byte of in_text.
2145
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2146
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2147
557k
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2148
557k
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2149
557k
    }
2150
2151
12.3M
    return wanted;
2152
12.3M
}
2153
2154
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2155
0
{
2156
0
    ImWchar* buf_out = buf;
2157
0
    ImWchar* buf_end = buf + buf_size;
2158
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2159
0
    {
2160
0
        unsigned int c;
2161
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2162
0
        *buf_out++ = (ImWchar)c;
2163
0
    }
2164
0
    *buf_out = 0;
2165
0
    if (in_text_remaining)
2166
0
        *in_text_remaining = in_text;
2167
0
    return (int)(buf_out - buf);
2168
0
}
2169
2170
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2171
0
{
2172
0
    int char_count = 0;
2173
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2174
0
    {
2175
0
        unsigned int c;
2176
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2177
0
        char_count++;
2178
0
    }
2179
0
    return char_count;
2180
0
}
2181
2182
// Based on stb_to_utf8() from github.com/nothings/stb/
2183
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2184
0
{
2185
0
    if (c < 0x80)
2186
0
    {
2187
0
        buf[0] = (char)c;
2188
0
        return 1;
2189
0
    }
2190
0
    if (c < 0x800)
2191
0
    {
2192
0
        if (buf_size < 2) return 0;
2193
0
        buf[0] = (char)(0xc0 + (c >> 6));
2194
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2195
0
        return 2;
2196
0
    }
2197
0
    if (c < 0x10000)
2198
0
    {
2199
0
        if (buf_size < 3) return 0;
2200
0
        buf[0] = (char)(0xe0 + (c >> 12));
2201
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2202
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2203
0
        return 3;
2204
0
    }
2205
0
    if (c <= 0x10FFFF)
2206
0
    {
2207
0
        if (buf_size < 4) return 0;
2208
0
        buf[0] = (char)(0xf0 + (c >> 18));
2209
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2210
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2211
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2212
0
        return 4;
2213
0
    }
2214
    // Invalid code point, the max unicode is 0x10FFFF
2215
0
    return 0;
2216
0
}
2217
2218
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2219
0
{
2220
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2221
0
    out_buf[count] = 0;
2222
0
    return out_buf;
2223
0
}
2224
2225
// Not optimal but we very rarely use this function.
2226
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2227
0
{
2228
0
    unsigned int unused = 0;
2229
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2230
0
}
2231
2232
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2233
0
{
2234
0
    if (c < 0x80) return 1;
2235
0
    if (c < 0x800) return 2;
2236
0
    if (c < 0x10000) return 3;
2237
0
    if (c <= 0x10FFFF) return 4;
2238
0
    return 3;
2239
0
}
2240
2241
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2242
0
{
2243
0
    char* buf_p = out_buf;
2244
0
    const char* buf_end = out_buf + out_buf_size;
2245
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2246
0
    {
2247
0
        unsigned int c = (unsigned int)(*in_text++);
2248
0
        if (c < 0x80)
2249
0
            *buf_p++ = (char)c;
2250
0
        else
2251
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2252
0
    }
2253
0
    *buf_p = 0;
2254
0
    return (int)(buf_p - out_buf);
2255
0
}
2256
2257
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2258
0
{
2259
0
    int bytes_count = 0;
2260
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2261
0
    {
2262
0
        unsigned int c = (unsigned int)(*in_text++);
2263
0
        if (c < 0x80)
2264
0
            bytes_count++;
2265
0
        else
2266
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2267
0
    }
2268
0
    return bytes_count;
2269
0
}
2270
IM_MSVC_RUNTIME_CHECKS_RESTORE
2271
2272
//-----------------------------------------------------------------------------
2273
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2274
// Note: The Convert functions are early design which are not consistent with other API.
2275
//-----------------------------------------------------------------------------
2276
2277
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2278
0
{
2279
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2280
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2281
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2282
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2283
0
    return IM_COL32(r, g, b, 0xFF);
2284
0
}
2285
2286
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2287
134k
{
2288
134k
    float s = 1.0f / 255.0f;
2289
134k
    return ImVec4(
2290
134k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2291
134k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2292
134k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2293
134k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2294
134k
}
2295
2296
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2297
724k
{
2298
724k
    ImU32 out;
2299
724k
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2300
724k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2301
724k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2302
724k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2303
724k
    return out;
2304
724k
}
2305
2306
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2307
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2308
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2309
0
{
2310
0
    float K = 0.f;
2311
0
    if (g < b)
2312
0
    {
2313
0
        ImSwap(g, b);
2314
0
        K = -1.f;
2315
0
    }
2316
0
    if (r < g)
2317
0
    {
2318
0
        ImSwap(r, g);
2319
0
        K = -2.f / 6.f - K;
2320
0
    }
2321
2322
0
    const float chroma = r - (g < b ? g : b);
2323
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2324
0
    out_s = chroma / (r + 1e-20f);
2325
0
    out_v = r;
2326
0
}
2327
2328
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2329
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2330
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2331
0
{
2332
0
    if (s == 0.0f)
2333
0
    {
2334
        // gray
2335
0
        out_r = out_g = out_b = v;
2336
0
        return;
2337
0
    }
2338
2339
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2340
0
    int   i = (int)h;
2341
0
    float f = h - (float)i;
2342
0
    float p = v * (1.0f - s);
2343
0
    float q = v * (1.0f - s * f);
2344
0
    float t = v * (1.0f - s * (1.0f - f));
2345
2346
0
    switch (i)
2347
0
    {
2348
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2349
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2350
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2351
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2352
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2353
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2354
0
    }
2355
0
}
2356
2357
//-----------------------------------------------------------------------------
2358
// [SECTION] ImGuiStorage
2359
// Helper: Key->value storage
2360
//-----------------------------------------------------------------------------
2361
2362
// std::lower_bound but without the bullshit
2363
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2364
107k
{
2365
107k
    ImGuiStorage::ImGuiStoragePair* first = data.Data;
2366
107k
    ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2367
107k
    size_t count = (size_t)(last - first);
2368
323k
    while (count > 0)
2369
215k
    {
2370
215k
        size_t count2 = count >> 1;
2371
215k
        ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2372
215k
        if (mid->key < key)
2373
71.8k
        {
2374
71.8k
            first = ++mid;
2375
71.8k
            count -= count2 + 1;
2376
71.8k
        }
2377
143k
        else
2378
143k
        {
2379
143k
            count = count2;
2380
143k
        }
2381
215k
    }
2382
107k
    return first;
2383
107k
}
2384
2385
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2386
void ImGuiStorage::BuildSortByKey()
2387
0
{
2388
0
    struct StaticFunc
2389
0
    {
2390
0
        static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2391
0
        {
2392
            // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2393
0
            if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2394
0
            if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2395
0
            return 0;
2396
0
        }
2397
0
    };
2398
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
2399
0
}
2400
2401
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2402
0
{
2403
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2404
0
    if (it == Data.end() || it->key != key)
2405
0
        return default_val;
2406
0
    return it->val_i;
2407
0
}
2408
2409
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2410
0
{
2411
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2412
0
}
2413
2414
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2415
0
{
2416
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2417
0
    if (it == Data.end() || it->key != key)
2418
0
        return default_val;
2419
0
    return it->val_f;
2420
0
}
2421
2422
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2423
107k
{
2424
107k
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2425
107k
    if (it == Data.end() || it->key != key)
2426
3
        return NULL;
2427
107k
    return it->val_p;
2428
107k
}
2429
2430
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2431
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2432
0
{
2433
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2434
0
    if (it == Data.end() || it->key != key)
2435
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2436
0
    return &it->val_i;
2437
0
}
2438
2439
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2440
0
{
2441
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2442
0
}
2443
2444
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2445
0
{
2446
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2447
0
    if (it == Data.end() || it->key != key)
2448
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2449
0
    return &it->val_f;
2450
0
}
2451
2452
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2453
0
{
2454
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2455
0
    if (it == Data.end() || it->key != key)
2456
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2457
0
    return &it->val_p;
2458
0
}
2459
2460
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2461
void ImGuiStorage::SetInt(ImGuiID key, int val)
2462
0
{
2463
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2464
0
    if (it == Data.end() || it->key != key)
2465
0
    {
2466
0
        Data.insert(it, ImGuiStoragePair(key, val));
2467
0
        return;
2468
0
    }
2469
0
    it->val_i = val;
2470
0
}
2471
2472
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2473
0
{
2474
0
    SetInt(key, val ? 1 : 0);
2475
0
}
2476
2477
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2478
0
{
2479
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2480
0
    if (it == Data.end() || it->key != key)
2481
0
    {
2482
0
        Data.insert(it, ImGuiStoragePair(key, val));
2483
0
        return;
2484
0
    }
2485
0
    it->val_f = val;
2486
0
}
2487
2488
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2489
3
{
2490
3
    ImGuiStoragePair* it = LowerBound(Data, key);
2491
3
    if (it == Data.end() || it->key != key)
2492
3
    {
2493
3
        Data.insert(it, ImGuiStoragePair(key, val));
2494
3
        return;
2495
3
    }
2496
0
    it->val_p = val;
2497
0
}
2498
2499
void ImGuiStorage::SetAllInt(int v)
2500
0
{
2501
0
    for (int i = 0; i < Data.Size; i++)
2502
0
        Data[i].val_i = v;
2503
0
}
2504
2505
//-----------------------------------------------------------------------------
2506
// [SECTION] ImGuiTextFilter
2507
//-----------------------------------------------------------------------------
2508
2509
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2510
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2511
0
{
2512
0
    InputBuf[0] = 0;
2513
0
    CountGrep = 0;
2514
0
    if (default_filter)
2515
0
    {
2516
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2517
0
        Build();
2518
0
    }
2519
0
}
2520
2521
bool ImGuiTextFilter::Draw(const char* label, float width)
2522
0
{
2523
0
    if (width != 0.0f)
2524
0
        ImGui::SetNextItemWidth(width);
2525
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2526
0
    if (value_changed)
2527
0
        Build();
2528
0
    return value_changed;
2529
0
}
2530
2531
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2532
0
{
2533
0
    out->resize(0);
2534
0
    const char* wb = b;
2535
0
    const char* we = wb;
2536
0
    while (we < e)
2537
0
    {
2538
0
        if (*we == separator)
2539
0
        {
2540
0
            out->push_back(ImGuiTextRange(wb, we));
2541
0
            wb = we + 1;
2542
0
        }
2543
0
        we++;
2544
0
    }
2545
0
    if (wb != we)
2546
0
        out->push_back(ImGuiTextRange(wb, we));
2547
0
}
2548
2549
void ImGuiTextFilter::Build()
2550
0
{
2551
0
    Filters.resize(0);
2552
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2553
0
    input_range.split(',', &Filters);
2554
2555
0
    CountGrep = 0;
2556
0
    for (int i = 0; i != Filters.Size; i++)
2557
0
    {
2558
0
        ImGuiTextRange& f = Filters[i];
2559
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2560
0
            f.b++;
2561
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2562
0
            f.e--;
2563
0
        if (f.empty())
2564
0
            continue;
2565
0
        if (Filters[i].b[0] != '-')
2566
0
            CountGrep += 1;
2567
0
    }
2568
0
}
2569
2570
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2571
0
{
2572
0
    if (Filters.empty())
2573
0
        return true;
2574
2575
0
    if (text == NULL)
2576
0
        text = "";
2577
2578
0
    for (int i = 0; i != Filters.Size; i++)
2579
0
    {
2580
0
        const ImGuiTextRange& f = Filters[i];
2581
0
        if (f.empty())
2582
0
            continue;
2583
0
        if (f.b[0] == '-')
2584
0
        {
2585
            // Subtract
2586
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2587
0
                return false;
2588
0
        }
2589
0
        else
2590
0
        {
2591
            // Grep
2592
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2593
0
                return true;
2594
0
        }
2595
0
    }
2596
2597
    // Implicit * grep
2598
0
    if (CountGrep == 0)
2599
0
        return true;
2600
2601
0
    return false;
2602
0
}
2603
2604
//-----------------------------------------------------------------------------
2605
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2606
//-----------------------------------------------------------------------------
2607
2608
// On some platform vsnprintf() takes va_list by reference and modifies it.
2609
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2610
#ifndef va_copy
2611
#if defined(__GNUC__) || defined(__clang__)
2612
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2613
#else
2614
#define va_copy(dest, src) (dest = src)
2615
#endif
2616
#endif
2617
2618
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2619
2620
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2621
0
{
2622
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2623
2624
    // Add zero-terminator the first time
2625
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2626
0
    const int needed_sz = write_off + len;
2627
0
    if (write_off + len >= Buf.Capacity)
2628
0
    {
2629
0
        int new_capacity = Buf.Capacity * 2;
2630
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2631
0
    }
2632
2633
0
    Buf.resize(needed_sz);
2634
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2635
0
    Buf[write_off - 1 + len] = 0;
2636
0
}
2637
2638
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2639
0
{
2640
0
    va_list args;
2641
0
    va_start(args, fmt);
2642
0
    appendfv(fmt, args);
2643
0
    va_end(args);
2644
0
}
2645
2646
// Helper: Text buffer for logging/accumulating text
2647
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2648
0
{
2649
0
    va_list args_copy;
2650
0
    va_copy(args_copy, args);
2651
2652
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2653
0
    if (len <= 0)
2654
0
    {
2655
0
        va_end(args_copy);
2656
0
        return;
2657
0
    }
2658
2659
    // Add zero-terminator the first time
2660
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2661
0
    const int needed_sz = write_off + len;
2662
0
    if (write_off + len >= Buf.Capacity)
2663
0
    {
2664
0
        int new_capacity = Buf.Capacity * 2;
2665
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2666
0
    }
2667
2668
0
    Buf.resize(needed_sz);
2669
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2670
0
    va_end(args_copy);
2671
0
}
2672
2673
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2674
0
{
2675
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2676
0
    if (old_size == new_size)
2677
0
        return;
2678
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2679
0
        LineOffsets.push_back(EndOffset);
2680
0
    const char* base_end = base + new_size;
2681
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2682
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2683
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2684
0
    EndOffset = ImMax(EndOffset, new_size);
2685
0
}
2686
2687
//-----------------------------------------------------------------------------
2688
// [SECTION] ImGuiListClipper
2689
// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
2690
// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
2691
//-----------------------------------------------------------------------------
2692
2693
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2694
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2695
static bool GetSkipItemForListClipping()
2696
0
{
2697
0
    ImGuiContext& g = *GImGui;
2698
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2699
0
}
2700
2701
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
2702
// Legacy helper to calculate coarse clipping of large list of evenly sized items.
2703
// This legacy API is not ideal because it assumes we will return a single contiguous rectangle.
2704
// Prefer using ImGuiListClipper which can returns non-contiguous ranges.
2705
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
2706
{
2707
    ImGuiContext& g = *GImGui;
2708
    ImGuiWindow* window = g.CurrentWindow;
2709
    if (g.LogEnabled)
2710
    {
2711
        // If logging is active, do not perform any clipping
2712
        *out_items_display_start = 0;
2713
        *out_items_display_end = items_count;
2714
        return;
2715
    }
2716
    if (GetSkipItemForListClipping())
2717
    {
2718
        *out_items_display_start = *out_items_display_end = 0;
2719
        return;
2720
    }
2721
2722
    // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect
2723
    // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly.
2724
    ImRect rect = window->ClipRect;
2725
    if (g.NavMoveScoringItems)
2726
        rect.Add(g.NavScoringNoClipRect);
2727
    if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
2728
        rect.Add(WindowRectRelToAbs(window, window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel
2729
2730
    const ImVec2 pos = window->DC.CursorPos;
2731
    int start = (int)((rect.Min.y - pos.y) / items_height);
2732
    int end = (int)((rect.Max.y - pos.y) / items_height);
2733
2734
    // When performing a navigation request, ensure we have one item extra in the direction we are moving to
2735
    // FIXME: Verify this works with tabbing
2736
    const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2737
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up)
2738
        start--;
2739
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down)
2740
        end++;
2741
2742
    start = ImClamp(start, 0, items_count);
2743
    end = ImClamp(end + 1, start, items_count);
2744
    *out_items_display_start = start;
2745
    *out_items_display_end = end;
2746
}
2747
#endif
2748
2749
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2750
0
{
2751
0
    if (ranges.Size - offset <= 1)
2752
0
        return;
2753
2754
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2755
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2756
0
        for (int i = offset; i < sort_end + offset; ++i)
2757
0
            if (ranges[i].Min > ranges[i + 1].Min)
2758
0
                ImSwap(ranges[i], ranges[i + 1]);
2759
2760
    // Now fuse ranges together as much as possible.
2761
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2762
0
    {
2763
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2764
0
        if (ranges[i - 1].Max < ranges[i].Min)
2765
0
            continue;
2766
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2767
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2768
0
        ranges.erase(ranges.Data + i);
2769
0
        i--;
2770
0
    }
2771
0
}
2772
2773
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2774
0
{
2775
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2776
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2777
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2778
0
    ImGuiContext& g = *GImGui;
2779
0
    ImGuiWindow* window = g.CurrentWindow;
2780
0
    float off_y = pos_y - window->DC.CursorPos.y;
2781
0
    window->DC.CursorPos.y = pos_y;
2782
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2783
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2784
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2785
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2786
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2787
0
    if (ImGuiTable* table = g.CurrentTable)
2788
0
    {
2789
0
        if (table->IsInsideRow)
2790
0
            ImGui::TableEndRow(table);
2791
0
        table->RowPosY2 = window->DC.CursorPos.y;
2792
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2793
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2794
0
        table->RowBgColorCounter += row_increase;
2795
0
    }
2796
0
}
2797
2798
static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2799
0
{
2800
    // StartPosY starts from ItemsFrozen hence the subtraction
2801
    // Perform the add and multiply with double to allow seeking through larger ranges
2802
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2803
0
    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2804
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2805
0
}
2806
2807
ImGuiListClipper::ImGuiListClipper()
2808
0
{
2809
0
    memset(this, 0, sizeof(*this));
2810
0
    Ctx = ImGui::GetCurrentContext();
2811
0
    IM_ASSERT(Ctx != NULL);
2812
0
    ItemsCount = -1;
2813
0
}
2814
2815
ImGuiListClipper::~ImGuiListClipper()
2816
0
{
2817
0
    End();
2818
0
}
2819
2820
void ImGuiListClipper::Begin(int items_count, float items_height)
2821
0
{
2822
0
    ImGuiContext& g = *Ctx;
2823
0
    ImGuiWindow* window = g.CurrentWindow;
2824
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2825
2826
0
    if (ImGuiTable* table = g.CurrentTable)
2827
0
        if (table->IsInsideRow)
2828
0
            ImGui::TableEndRow(table);
2829
2830
0
    StartPosY = window->DC.CursorPos.y;
2831
0
    ItemsHeight = items_height;
2832
0
    ItemsCount = items_count;
2833
0
    DisplayStart = -1;
2834
0
    DisplayEnd = 0;
2835
2836
    // Acquire temporary buffer
2837
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2838
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
2839
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2840
0
    data->Reset(this);
2841
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2842
0
    TempData = data;
2843
0
}
2844
2845
void ImGuiListClipper::End()
2846
0
{
2847
0
    ImGuiContext& g = *Ctx;
2848
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2849
0
    {
2850
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
2851
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2852
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2853
0
            ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
2854
2855
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2856
0
        IM_ASSERT(data->ListClipper == this);
2857
0
        data->StepNo = data->Ranges.Size;
2858
0
        if (--g.ClipperTempDataStacked > 0)
2859
0
        {
2860
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2861
0
            data->ListClipper->TempData = data;
2862
0
        }
2863
0
        TempData = NULL;
2864
0
    }
2865
0
    ItemsCount = -1;
2866
0
}
2867
2868
void ImGuiListClipper::IncludeRangeByIndices(int item_begin, int item_end)
2869
0
{
2870
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2871
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2872
0
    IM_ASSERT(item_begin <= item_end);
2873
0
    if (item_begin < item_end)
2874
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
2875
0
}
2876
2877
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2878
0
{
2879
0
    ImGuiContext& g = *clipper->Ctx;
2880
0
    ImGuiWindow* window = g.CurrentWindow;
2881
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2882
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2883
2884
0
    ImGuiTable* table = g.CurrentTable;
2885
0
    if (table && table->IsInsideRow)
2886
0
        ImGui::TableEndRow(table);
2887
2888
    // No items
2889
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2890
0
        return false;
2891
2892
    // While we are in frozen row state, keep displaying items one by one, unclipped
2893
    // FIXME: Could be stored as a table-agnostic state.
2894
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2895
0
    {
2896
0
        clipper->DisplayStart = data->ItemsFrozen;
2897
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
2898
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
2899
0
            data->ItemsFrozen++;
2900
0
        return true;
2901
0
    }
2902
2903
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2904
0
    bool calc_clipping = false;
2905
0
    if (data->StepNo == 0)
2906
0
    {
2907
0
        clipper->StartPosY = window->DC.CursorPos.y;
2908
0
        if (clipper->ItemsHeight <= 0.0f)
2909
0
        {
2910
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2911
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
2912
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
2913
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
2914
0
            data->StepNo = 1;
2915
0
            return true;
2916
0
        }
2917
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
2918
0
    }
2919
2920
    // Step 1: Let the clipper infer height from first range
2921
0
    if (clipper->ItemsHeight <= 0.0f)
2922
0
    {
2923
0
        IM_ASSERT(data->StepNo == 1);
2924
0
        if (table)
2925
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
2926
2927
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
2928
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
2929
0
        if (affected_by_floating_point_precision)
2930
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
2931
2932
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
2933
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
2934
0
    }
2935
2936
    // Step 0 or 1: Calculate the actual ranges of visible elements.
2937
0
    const int already_submitted = clipper->DisplayEnd;
2938
0
    if (calc_clipping)
2939
0
    {
2940
0
        if (g.LogEnabled)
2941
0
        {
2942
            // If logging is active, do not perform any clipping
2943
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
2944
0
        }
2945
0
        else
2946
0
        {
2947
            // Add range selected to be included for navigation
2948
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2949
0
            if (is_nav_request)
2950
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
2951
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && g.NavTabbingDir == -1)
2952
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
2953
2954
            // Add focused/active item
2955
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
2956
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
2957
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
2958
2959
            // Add visible range
2960
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
2961
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
2962
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
2963
0
        }
2964
2965
        // Convert position ranges to item index ranges
2966
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
2967
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
2968
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
2969
0
        for (int i = 0; i < data->Ranges.Size; i++)
2970
0
            if (data->Ranges[i].PosToIndexConvert)
2971
0
            {
2972
0
                int m1 = (int)(((double)data->Ranges[i].Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
2973
0
                int m2 = (int)((((double)data->Ranges[i].Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
2974
0
                data->Ranges[i].Min = ImClamp(already_submitted + m1 + data->Ranges[i].PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
2975
0
                data->Ranges[i].Max = ImClamp(already_submitted + m2 + data->Ranges[i].PosToIndexOffsetMax, data->Ranges[i].Min + 1, clipper->ItemsCount);
2976
0
                data->Ranges[i].PosToIndexConvert = false;
2977
0
            }
2978
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
2979
0
    }
2980
2981
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
2982
0
    if (data->StepNo < data->Ranges.Size)
2983
0
    {
2984
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
2985
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
2986
0
        if (clipper->DisplayStart > already_submitted) //-V1051
2987
0
            ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
2988
0
        data->StepNo++;
2989
0
        return true;
2990
0
    }
2991
2992
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
2993
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
2994
0
    if (clipper->ItemsCount < INT_MAX)
2995
0
        ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
2996
2997
0
    return false;
2998
0
}
2999
3000
bool ImGuiListClipper::Step()
3001
0
{
3002
0
    ImGuiContext& g = *Ctx;
3003
0
    bool need_items_height = (ItemsHeight <= 0.0f);
3004
0
    bool ret = ImGuiListClipper_StepInternal(this);
3005
0
    if (ret && (DisplayStart == DisplayEnd))
3006
0
        ret = false;
3007
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3008
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3009
0
    if (need_items_height && ItemsHeight > 0.0f)
3010
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3011
0
    if (ret)
3012
0
    {
3013
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3014
0
    }
3015
0
    else
3016
0
    {
3017
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3018
0
        End();
3019
0
    }
3020
0
    return ret;
3021
0
}
3022
3023
//-----------------------------------------------------------------------------
3024
// [SECTION] STYLING
3025
//-----------------------------------------------------------------------------
3026
3027
ImGuiStyle& ImGui::GetStyle()
3028
98.7k
{
3029
98.7k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3030
98.7k
    return GImGui->Style;
3031
98.7k
}
3032
3033
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3034
625k
{
3035
625k
    ImGuiStyle& style = GImGui->Style;
3036
625k
    ImVec4 c = style.Colors[idx];
3037
625k
    c.w *= style.Alpha * alpha_mul;
3038
625k
    return ColorConvertFloat4ToU32(c);
3039
625k
}
3040
3041
ImU32 ImGui::GetColorU32(const ImVec4& col)
3042
0
{
3043
0
    ImGuiStyle& style = GImGui->Style;
3044
0
    ImVec4 c = col;
3045
0
    c.w *= style.Alpha;
3046
0
    return ColorConvertFloat4ToU32(c);
3047
0
}
3048
3049
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3050
0
{
3051
0
    ImGuiStyle& style = GImGui->Style;
3052
0
    return style.Colors[idx];
3053
0
}
3054
3055
ImU32 ImGui::GetColorU32(ImU32 col)
3056
0
{
3057
0
    ImGuiStyle& style = GImGui->Style;
3058
0
    if (style.Alpha >= 1.0f)
3059
0
        return col;
3060
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3061
0
    a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
3062
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3063
0
}
3064
3065
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3066
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3067
0
{
3068
0
    ImGuiContext& g = *GImGui;
3069
0
    ImGuiColorMod backup;
3070
0
    backup.Col = idx;
3071
0
    backup.BackupValue = g.Style.Colors[idx];
3072
0
    g.ColorStack.push_back(backup);
3073
0
    g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3074
0
}
3075
3076
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3077
35.9k
{
3078
35.9k
    ImGuiContext& g = *GImGui;
3079
35.9k
    ImGuiColorMod backup;
3080
35.9k
    backup.Col = idx;
3081
35.9k
    backup.BackupValue = g.Style.Colors[idx];
3082
35.9k
    g.ColorStack.push_back(backup);
3083
35.9k
    g.Style.Colors[idx] = col;
3084
35.9k
}
3085
3086
void ImGui::PopStyleColor(int count)
3087
35.9k
{
3088
35.9k
    ImGuiContext& g = *GImGui;
3089
35.9k
    if (g.ColorStack.Size < count)
3090
0
    {
3091
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times: stack underflow.");
3092
0
        count = g.ColorStack.Size;
3093
0
    }
3094
71.8k
    while (count > 0)
3095
35.9k
    {
3096
35.9k
        ImGuiColorMod& backup = g.ColorStack.back();
3097
35.9k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3098
35.9k
        g.ColorStack.pop_back();
3099
35.9k
        count--;
3100
35.9k
    }
3101
35.9k
}
3102
3103
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3104
{
3105
    ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3106
};
3107
3108
static const ImGuiDataVarInfo GStyleVarInfo[] =
3109
{
3110
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) },               // ImGuiStyleVar_Alpha
3111
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DisabledAlpha) },       // ImGuiStyleVar_DisabledAlpha
3112
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) },       // ImGuiStyleVar_WindowPadding
3113
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) },      // ImGuiStyleVar_WindowRounding
3114
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) },    // ImGuiStyleVar_WindowBorderSize
3115
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) },       // ImGuiStyleVar_WindowMinSize
3116
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) },    // ImGuiStyleVar_WindowTitleAlign
3117
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) },       // ImGuiStyleVar_ChildRounding
3118
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) },     // ImGuiStyleVar_ChildBorderSize
3119
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) },       // ImGuiStyleVar_PopupRounding
3120
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) },     // ImGuiStyleVar_PopupBorderSize
3121
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) },        // ImGuiStyleVar_FramePadding
3122
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) },       // ImGuiStyleVar_FrameRounding
3123
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) },     // ImGuiStyleVar_FrameBorderSize
3124
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) },         // ImGuiStyleVar_ItemSpacing
3125
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) },    // ImGuiStyleVar_ItemInnerSpacing
3126
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) },       // ImGuiStyleVar_IndentSpacing
3127
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) },         // ImGuiStyleVar_CellPadding
3128
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) },       // ImGuiStyleVar_ScrollbarSize
3129
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) },   // ImGuiStyleVar_ScrollbarRounding
3130
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) },         // ImGuiStyleVar_GrabMinSize
3131
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) },        // ImGuiStyleVar_GrabRounding
3132
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) },         // ImGuiStyleVar_TabRounding
3133
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) },     // ImGuiStyleVar_ButtonTextAlign
3134
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3135
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextBorderSize) },// ImGuiStyleVar_SeparatorTextBorderSize
3136
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextAlign) },     // ImGuiStyleVar_SeparatorTextAlign
3137
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextPadding) },   // ImGuiStyleVar_SeparatorTextPadding
3138
};
3139
3140
const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3141
71.8k
{
3142
71.8k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3143
71.8k
    IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3144
71.8k
    return &GStyleVarInfo[idx];
3145
71.8k
}
3146
3147
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3148
0
{
3149
0
    ImGuiContext& g = *GImGui;
3150
0
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3151
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3152
0
    {
3153
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3154
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3155
0
        *pvar = val;
3156
0
        return;
3157
0
    }
3158
0
    IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3159
0
}
3160
3161
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3162
35.9k
{
3163
35.9k
    ImGuiContext& g = *GImGui;
3164
35.9k
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3165
35.9k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3166
35.9k
    {
3167
35.9k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3168
35.9k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3169
35.9k
        *pvar = val;
3170
35.9k
        return;
3171
35.9k
    }
3172
0
    IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3173
0
}
3174
3175
void ImGui::PopStyleVar(int count)
3176
35.9k
{
3177
35.9k
    ImGuiContext& g = *GImGui;
3178
35.9k
    if (g.StyleVarStack.Size < count)
3179
0
    {
3180
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times: stack underflow.");
3181
0
        count = g.StyleVarStack.Size;
3182
0
    }
3183
71.8k
    while (count > 0)
3184
35.9k
    {
3185
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3186
35.9k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3187
35.9k
        const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3188
35.9k
        void* data = info->GetVarPtr(&g.Style);
3189
35.9k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3190
35.9k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3191
35.9k
        g.StyleVarStack.pop_back();
3192
35.9k
        count--;
3193
35.9k
    }
3194
35.9k
}
3195
3196
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3197
0
{
3198
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3199
0
    switch (idx)
3200
0
    {
3201
0
    case ImGuiCol_Text: return "Text";
3202
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3203
0
    case ImGuiCol_WindowBg: return "WindowBg";
3204
0
    case ImGuiCol_ChildBg: return "ChildBg";
3205
0
    case ImGuiCol_PopupBg: return "PopupBg";
3206
0
    case ImGuiCol_Border: return "Border";
3207
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3208
0
    case ImGuiCol_FrameBg: return "FrameBg";
3209
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3210
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3211
0
    case ImGuiCol_TitleBg: return "TitleBg";
3212
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3213
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3214
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3215
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3216
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3217
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3218
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3219
0
    case ImGuiCol_CheckMark: return "CheckMark";
3220
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3221
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3222
0
    case ImGuiCol_Button: return "Button";
3223
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3224
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3225
0
    case ImGuiCol_Header: return "Header";
3226
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3227
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3228
0
    case ImGuiCol_Separator: return "Separator";
3229
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3230
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3231
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3232
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3233
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3234
0
    case ImGuiCol_Tab: return "Tab";
3235
0
    case ImGuiCol_TabHovered: return "TabHovered";
3236
0
    case ImGuiCol_TabActive: return "TabActive";
3237
0
    case ImGuiCol_TabUnfocused: return "TabUnfocused";
3238
0
    case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3239
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3240
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3241
0
    case ImGuiCol_PlotLines: return "PlotLines";
3242
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3243
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3244
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3245
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3246
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3247
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3248
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3249
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3250
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3251
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3252
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3253
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3254
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3255
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3256
0
    }
3257
0
    IM_ASSERT(0);
3258
0
    return "Unknown";
3259
0
}
3260
3261
3262
//-----------------------------------------------------------------------------
3263
// [SECTION] RENDER HELPERS
3264
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3265
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3266
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3267
//-----------------------------------------------------------------------------
3268
3269
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3270
143k
{
3271
143k
    const char* text_display_end = text;
3272
143k
    if (!text_end)
3273
143k
        text_end = (const char*)-1;
3274
3275
1.29M
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3276
1.14M
        text_display_end++;
3277
143k
    return text_display_end;
3278
143k
}
3279
3280
// Internal ImGui functions to render text
3281
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3282
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3283
0
{
3284
0
    ImGuiContext& g = *GImGui;
3285
0
    ImGuiWindow* window = g.CurrentWindow;
3286
3287
    // Hide anything after a '##' string
3288
0
    const char* text_display_end;
3289
0
    if (hide_text_after_hash)
3290
0
    {
3291
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3292
0
    }
3293
0
    else
3294
0
    {
3295
0
        if (!text_end)
3296
0
            text_end = text + strlen(text); // FIXME-OPT
3297
0
        text_display_end = text_end;
3298
0
    }
3299
3300
0
    if (text != text_display_end)
3301
0
    {
3302
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3303
0
        if (g.LogEnabled)
3304
0
            LogRenderedText(&pos, text, text_display_end);
3305
0
    }
3306
0
}
3307
3308
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3309
0
{
3310
0
    ImGuiContext& g = *GImGui;
3311
0
    ImGuiWindow* window = g.CurrentWindow;
3312
3313
0
    if (!text_end)
3314
0
        text_end = text + strlen(text); // FIXME-OPT
3315
3316
0
    if (text != text_end)
3317
0
    {
3318
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3319
0
        if (g.LogEnabled)
3320
0
            LogRenderedText(&pos, text, text_end);
3321
0
    }
3322
0
}
3323
3324
// Default clip_rect uses (pos_min,pos_max)
3325
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3326
// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3327
// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3328
// better advantage of the render function taking size into account for coarse clipping.
3329
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3330
71.8k
{
3331
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3332
71.8k
    ImVec2 pos = pos_min;
3333
71.8k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3334
3335
71.8k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3336
71.8k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3337
71.8k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3338
71.8k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3339
71.8k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3340
3341
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3342
71.8k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3343
71.8k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3344
3345
    // Render
3346
71.8k
    if (need_clipping)
3347
1
    {
3348
1
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3349
1
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3350
1
    }
3351
71.8k
    else
3352
71.8k
    {
3353
71.8k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3354
71.8k
    }
3355
71.8k
}
3356
3357
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3358
71.8k
{
3359
    // Hide anything after a '##' string
3360
71.8k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3361
71.8k
    const int text_len = (int)(text_display_end - text);
3362
71.8k
    if (text_len == 0)
3363
0
        return;
3364
3365
71.8k
    ImGuiContext& g = *GImGui;
3366
71.8k
    ImGuiWindow* window = g.CurrentWindow;
3367
71.8k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3368
71.8k
    if (g.LogEnabled)
3369
0
        LogRenderedText(&pos_min, text, text_display_end);
3370
71.8k
}
3371
3372
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3373
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3374
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3375
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3376
0
{
3377
0
    ImGuiContext& g = *GImGui;
3378
0
    if (text_end_full == NULL)
3379
0
        text_end_full = FindRenderedTextEnd(text);
3380
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3381
3382
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3383
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3384
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3385
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3386
0
    if (text_size.x > pos_max.x - pos_min.x)
3387
0
    {
3388
        // Hello wo...
3389
        // |       |   |
3390
        // min   max   ellipsis_max
3391
        //          <-> this is generally some padding value
3392
3393
0
        const ImFont* font = draw_list->_Data->Font;
3394
0
        const float font_size = draw_list->_Data->FontSize;
3395
0
        const float font_scale = font_size / font->FontSize;
3396
0
        const char* text_end_ellipsis = NULL;
3397
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3398
3399
        // We can now claim the space between pos_max.x and ellipsis_max.x
3400
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3401
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3402
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3403
0
        {
3404
            // Always display at least 1 character if there's no room for character + ellipsis
3405
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3406
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3407
0
        }
3408
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3409
0
        {
3410
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3411
0
            text_end_ellipsis--;
3412
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3413
0
        }
3414
3415
        // Render text, render ellipsis
3416
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3417
0
        ImVec2 ellipsis_pos = ImFloor(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3418
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3419
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3420
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3421
0
    }
3422
0
    else
3423
0
    {
3424
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3425
0
    }
3426
3427
0
    if (g.LogEnabled)
3428
0
        LogRenderedText(&pos_min, text, text_end_full);
3429
0
}
3430
3431
// Render a rectangle shaped with optional rounding and borders
3432
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3433
0
{
3434
0
    ImGuiContext& g = *GImGui;
3435
0
    ImGuiWindow* window = g.CurrentWindow;
3436
0
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3437
0
    const float border_size = g.Style.FrameBorderSize;
3438
0
    if (border && border_size > 0.0f)
3439
0
    {
3440
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3441
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3442
0
    }
3443
0
}
3444
3445
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3446
0
{
3447
0
    ImGuiContext& g = *GImGui;
3448
0
    ImGuiWindow* window = g.CurrentWindow;
3449
0
    const float border_size = g.Style.FrameBorderSize;
3450
0
    if (border_size > 0.0f)
3451
0
    {
3452
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3453
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3454
0
    }
3455
0
}
3456
3457
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3458
60.0k
{
3459
60.0k
    ImGuiContext& g = *GImGui;
3460
60.0k
    if (id != g.NavId)
3461
30.1k
        return;
3462
29.8k
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3463
610
        return;
3464
29.2k
    ImGuiWindow* window = g.CurrentWindow;
3465
29.2k
    if (window->DC.NavHideHighlightOneFrame)
3466
0
        return;
3467
3468
29.2k
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3469
29.2k
    ImRect display_rect = bb;
3470
29.2k
    display_rect.ClipWith(window->ClipRect);
3471
29.2k
    if (flags & ImGuiNavHighlightFlags_TypeDefault)
3472
2.37k
    {
3473
2.37k
        const float THICKNESS = 2.0f;
3474
2.37k
        const float DISTANCE = 3.0f + THICKNESS * 0.5f;
3475
2.37k
        display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
3476
2.37k
        bool fully_visible = window->ClipRect.Contains(display_rect);
3477
2.37k
        if (!fully_visible)
3478
911
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3479
2.37k
        window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS);
3480
2.37k
        if (!fully_visible)
3481
911
            window->DrawList->PopClipRect();
3482
2.37k
    }
3483
29.2k
    if (flags & ImGuiNavHighlightFlags_TypeThin)
3484
26.8k
    {
3485
26.8k
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);
3486
26.8k
    }
3487
29.2k
}
3488
3489
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3490
0
{
3491
0
    ImGuiContext& g = *GImGui;
3492
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3493
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3494
0
    for (int n = 0; n < g.Viewports.Size; n++)
3495
0
    {
3496
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3497
0
        ImVec2 offset, size, uv[4];
3498
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3499
0
            continue;
3500
0
        ImGuiViewportP* viewport = g.Viewports[n];
3501
0
        const ImVec2 pos = base_pos - offset;
3502
0
        const float scale = base_scale * viewport->DpiScale;
3503
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3504
0
            continue;
3505
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3506
0
        ImTextureID tex_id = font_atlas->TexID;
3507
0
        draw_list->PushTextureID(tex_id);
3508
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3509
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3510
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3511
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3512
0
        draw_list->PopTextureID();
3513
0
    }
3514
0
}
3515
3516
//-----------------------------------------------------------------------------
3517
// [SECTION] INITIALIZATION, SHUTDOWN
3518
//-----------------------------------------------------------------------------
3519
3520
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3521
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3522
ImGuiContext* ImGui::GetCurrentContext()
3523
1
{
3524
1
    return GImGui;
3525
1
}
3526
3527
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3528
1
{
3529
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3530
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3531
#else
3532
1
    GImGui = ctx;
3533
1
#endif
3534
1
}
3535
3536
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3537
0
{
3538
0
    GImAllocatorAllocFunc = alloc_func;
3539
0
    GImAllocatorFreeFunc = free_func;
3540
0
    GImAllocatorUserData = user_data;
3541
0
}
3542
3543
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3544
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3545
0
{
3546
0
    *p_alloc_func = GImAllocatorAllocFunc;
3547
0
    *p_free_func = GImAllocatorFreeFunc;
3548
0
    *p_user_data = GImAllocatorUserData;
3549
0
}
3550
3551
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3552
1
{
3553
1
    ImGuiContext* prev_ctx = GetCurrentContext();
3554
1
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3555
1
    SetCurrentContext(ctx);
3556
1
    Initialize();
3557
1
    if (prev_ctx != NULL)
3558
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3559
1
    return ctx;
3560
1
}
3561
3562
void ImGui::DestroyContext(ImGuiContext* ctx)
3563
0
{
3564
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3565
0
    if (ctx == NULL) //-V1051
3566
0
        ctx = prev_ctx;
3567
0
    SetCurrentContext(ctx);
3568
0
    Shutdown();
3569
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3570
0
    IM_DELETE(ctx);
3571
0
}
3572
3573
// IMPORTANT: ###xxx suffixes must be same in ALL languages
3574
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3575
{
3576
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3577
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3578
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3579
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3580
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3581
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3582
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3583
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3584
};
3585
3586
void ImGui::Initialize()
3587
1
{
3588
1
    ImGuiContext& g = *GImGui;
3589
1
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3590
3591
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3592
1
    {
3593
1
        ImGuiSettingsHandler ini_handler;
3594
1
        ini_handler.TypeName = "Window";
3595
1
        ini_handler.TypeHash = ImHashStr("Window");
3596
1
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3597
1
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3598
1
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3599
1
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3600
1
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3601
1
        AddSettingsHandler(&ini_handler);
3602
1
    }
3603
1
    TableSettingsAddSettingsHandler();
3604
3605
    // Setup default localization table
3606
1
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3607
3608
    // Setup default platform clipboard/IME handlers.
3609
1
    g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;    // Platform dependent default implementations
3610
1
    g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3611
1
    g.IO.ClipboardUserData = (void*)&g;                          // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3612
1
    g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
3613
3614
    // Create default viewport
3615
1
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3616
1
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3617
1
    viewport->Idx = 0;
3618
1
    viewport->PlatformWindowCreated = true;
3619
1
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3620
1
    g.Viewports.push_back(viewport);
3621
1
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3622
1
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3623
3624
1
#ifdef IMGUI_HAS_DOCK
3625
    // Initialize Docking
3626
1
    DockContextInitialize(&g);
3627
1
#endif
3628
3629
1
    g.Initialized = true;
3630
1
}
3631
3632
// This function is merely here to free heap allocations.
3633
void ImGui::Shutdown()
3634
0
{
3635
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3636
0
    ImGuiContext& g = *GImGui;
3637
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3638
0
    {
3639
0
        g.IO.Fonts->Locked = false;
3640
0
        IM_DELETE(g.IO.Fonts);
3641
0
    }
3642
0
    g.IO.Fonts = NULL;
3643
0
    g.DrawListSharedData.TempBuffer.clear();
3644
3645
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3646
0
    if (!g.Initialized)
3647
0
        return;
3648
3649
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3650
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3651
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3652
3653
    // Destroy platform windows
3654
0
    DestroyPlatformWindows();
3655
3656
    // Shutdown extensions
3657
0
    DockContextShutdown(&g);
3658
3659
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3660
3661
    // Clear everything else
3662
0
    g.Windows.clear_delete();
3663
0
    g.WindowsFocusOrder.clear();
3664
0
    g.WindowsTempSortBuffer.clear();
3665
0
    g.CurrentWindow = NULL;
3666
0
    g.CurrentWindowStack.clear();
3667
0
    g.WindowsById.Clear();
3668
0
    g.NavWindow = NULL;
3669
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3670
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3671
0
    g.MovingWindow = NULL;
3672
3673
0
    g.KeysRoutingTable.Clear();
3674
3675
0
    g.ColorStack.clear();
3676
0
    g.StyleVarStack.clear();
3677
0
    g.FontStack.clear();
3678
0
    g.OpenPopupStack.clear();
3679
0
    g.BeginPopupStack.clear();
3680
3681
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3682
0
    g.Viewports.clear_delete();
3683
3684
0
    g.TabBars.Clear();
3685
0
    g.CurrentTabBarStack.clear();
3686
0
    g.ShrinkWidthBuffer.clear();
3687
3688
0
    g.ClipperTempData.clear_destruct();
3689
3690
0
    g.Tables.Clear();
3691
0
    g.TablesTempData.clear_destruct();
3692
0
    g.DrawChannelsTempMergeBuffer.clear();
3693
3694
0
    g.ClipboardHandlerData.clear();
3695
0
    g.MenusIdSubmittedThisFrame.clear();
3696
0
    g.InputTextState.ClearFreeMemory();
3697
0
    g.InputTextDeactivatedState.ClearFreeMemory();
3698
3699
0
    g.SettingsWindows.clear();
3700
0
    g.SettingsHandlers.clear();
3701
3702
0
    if (g.LogFile)
3703
0
    {
3704
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3705
0
        if (g.LogFile != stdout)
3706
0
#endif
3707
0
            ImFileClose(g.LogFile);
3708
0
        g.LogFile = NULL;
3709
0
    }
3710
0
    g.LogBuffer.clear();
3711
0
    g.DebugLogBuf.clear();
3712
0
    g.DebugLogIndex.clear();
3713
3714
0
    g.Initialized = false;
3715
0
}
3716
3717
// No specific ordering/dependency support, will see as needed
3718
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3719
0
{
3720
0
    ImGuiContext& g = *ctx;
3721
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3722
0
    g.Hooks.push_back(*hook);
3723
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3724
0
    return g.HookIdNext;
3725
0
}
3726
3727
// Deferred removal, avoiding issue with changing vector while iterating it
3728
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3729
0
{
3730
0
    ImGuiContext& g = *ctx;
3731
0
    IM_ASSERT(hook_id != 0);
3732
0
    for (int n = 0; n < g.Hooks.Size; n++)
3733
0
        if (g.Hooks[n].HookId == hook_id)
3734
0
            g.Hooks[n].Type = ImGuiContextHookType_PendingRemoval_;
3735
0
}
3736
3737
// Call context hooks (used by e.g. test engine)
3738
// We assume a small number of hooks so all stored in same array
3739
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3740
215k
{
3741
215k
    ImGuiContext& g = *ctx;
3742
215k
    for (int n = 0; n < g.Hooks.Size; n++)
3743
0
        if (g.Hooks[n].Type == hook_type)
3744
0
            g.Hooks[n].Callback(&g, &g.Hooks[n]);
3745
215k
}
3746
3747
3748
//-----------------------------------------------------------------------------
3749
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3750
//-----------------------------------------------------------------------------
3751
3752
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3753
ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3754
3
{
3755
3
    memset(this, 0, sizeof(*this));
3756
3
    Ctx = ctx;
3757
3
    Name = ImStrdup(name);
3758
3
    NameBufLen = (int)strlen(name) + 1;
3759
3
    ID = ImHashStr(name);
3760
3
    IDStack.push_back(ID);
3761
3
    ViewportAllowPlatformMonitorExtend = -1;
3762
3
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3763
3
    MoveId = GetID("#MOVE");
3764
3
    TabId = GetID("#TAB");
3765
3
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3766
3
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3767
3
    AutoFitFramesX = AutoFitFramesY = -1;
3768
3
    AutoPosLastDirection = ImGuiDir_None;
3769
3
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
3770
3
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3771
3
    LastFrameActive = -1;
3772
3
    LastFrameJustFocused = -1;
3773
3
    LastTimeActive = -1.0f;
3774
3
    FontWindowScale = FontDpiScale = 1.0f;
3775
3
    SettingsOffset = -1;
3776
3
    DockOrder = -1;
3777
3
    DrawList = &DrawListInst;
3778
3
    DrawList->_Data = &Ctx->DrawListSharedData;
3779
3
    DrawList->_OwnerName = Name;
3780
3
    NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
3781
3
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3782
3
}
3783
3784
ImGuiWindow::~ImGuiWindow()
3785
0
{
3786
0
    IM_ASSERT(DrawList == &DrawListInst);
3787
0
    IM_DELETE(Name);
3788
0
    ColumnsStorage.clear_destruct();
3789
0
}
3790
3791
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
3792
216k
{
3793
216k
    ImGuiID seed = IDStack.back();
3794
216k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
3795
216k
    ImGuiContext& g = *Ctx;
3796
216k
    if (g.DebugHookIdInfo == id)
3797
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
3798
216k
    return id;
3799
216k
}
3800
3801
ImGuiID ImGuiWindow::GetID(const void* ptr)
3802
0
{
3803
0
    ImGuiID seed = IDStack.back();
3804
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
3805
0
    ImGuiContext& g = *Ctx;
3806
0
    if (g.DebugHookIdInfo == id)
3807
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
3808
0
    return id;
3809
0
}
3810
3811
ImGuiID ImGuiWindow::GetID(int n)
3812
35.9k
{
3813
35.9k
    ImGuiID seed = IDStack.back();
3814
35.9k
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
3815
35.9k
    ImGuiContext& g = *Ctx;
3816
35.9k
    if (g.DebugHookIdInfo == id)
3817
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
3818
35.9k
    return id;
3819
35.9k
}
3820
3821
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
3822
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
3823
0
{
3824
0
    ImGuiID seed = IDStack.back();
3825
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
3826
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
3827
0
    return id;
3828
0
}
3829
3830
static void SetCurrentWindow(ImGuiWindow* window)
3831
215k
{
3832
215k
    ImGuiContext& g = *GImGui;
3833
215k
    g.CurrentWindow = window;
3834
215k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3835
215k
    if (window)
3836
179k
    {
3837
179k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3838
179k
        ImGui::NavUpdateCurrentWindowIsScrollPushableX();
3839
179k
    }
3840
215k
}
3841
3842
void ImGui::GcCompactTransientMiscBuffers()
3843
0
{
3844
0
    ImGuiContext& g = *GImGui;
3845
0
    g.ItemFlagsStack.clear();
3846
0
    g.GroupStack.clear();
3847
0
    TableGcCompactSettings();
3848
0
}
3849
3850
// Free up/compact internal window buffers, we can use this when a window becomes unused.
3851
// Not freed:
3852
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3853
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3854
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3855
0
{
3856
0
    window->MemoryCompacted = true;
3857
0
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3858
0
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3859
0
    window->IDStack.clear();
3860
0
    window->DrawList->_ClearFreeMemory();
3861
0
    window->DC.ChildWindows.clear();
3862
0
    window->DC.ItemWidthStack.clear();
3863
0
    window->DC.TextWrapPosStack.clear();
3864
0
}
3865
3866
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3867
0
{
3868
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3869
    // The other buffers tends to amortize much faster.
3870
0
    window->MemoryCompacted = false;
3871
0
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3872
0
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3873
0
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3874
0
}
3875
3876
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3877
565
{
3878
565
    ImGuiContext& g = *GImGui;
3879
3880
    // Clear previous active id
3881
565
    if (g.ActiveId != 0)
3882
12
    {
3883
        // While most behaved code would make an effort to not steal active id during window move/drag operations,
3884
        // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
3885
        // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3886
12
        if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3887
0
        {
3888
0
            IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3889
0
            g.MovingWindow = NULL;
3890
0
        }
3891
3892
        // This could be written in a more general way (e.g associate a hook to ActiveId),
3893
        // but since this is currently quite an exception we'll leave it as is.
3894
        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
3895
12
        if (g.InputTextState.ID == g.ActiveId)
3896
0
            InputTextDeactivateHook(g.ActiveId);
3897
12
    }
3898
3899
    // Set active id
3900
565
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
3901
565
    if (g.ActiveIdIsJustActivated)
3902
21
    {
3903
21
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
3904
21
        g.ActiveIdTimer = 0.0f;
3905
21
        g.ActiveIdHasBeenPressedBefore = false;
3906
21
        g.ActiveIdHasBeenEditedBefore = false;
3907
21
        g.ActiveIdMouseButton = -1;
3908
21
        if (id != 0)
3909
12
        {
3910
12
            g.LastActiveId = id;
3911
12
            g.LastActiveIdTimer = 0.0f;
3912
12
        }
3913
21
    }
3914
565
    g.ActiveId = id;
3915
565
    g.ActiveIdAllowOverlap = false;
3916
565
    g.ActiveIdNoClearOnFocusLoss = false;
3917
565
    g.ActiveIdWindow = window;
3918
565
    g.ActiveIdHasBeenEditedThisFrame = false;
3919
565
    if (id)
3920
12
    {
3921
12
        g.ActiveIdIsAlive = id;
3922
12
        g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
3923
12
        IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
3924
12
    }
3925
3926
    // Clear declaration of inputs claimed by the widget
3927
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
3928
565
    g.ActiveIdUsingNavDirMask = 0x00;
3929
565
    g.ActiveIdUsingAllKeyboardKeys = false;
3930
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
3931
    g.ActiveIdUsingNavInputMask = 0x00;
3932
#endif
3933
565
}
3934
3935
void ImGui::ClearActiveID()
3936
553
{
3937
553
    SetActiveID(0, NULL); // g.ActiveId = 0;
3938
553
}
3939
3940
void ImGui::SetHoveredID(ImGuiID id)
3941
360
{
3942
360
    ImGuiContext& g = *GImGui;
3943
360
    g.HoveredId = id;
3944
360
    g.HoveredIdAllowOverlap = false;
3945
360
    if (id != 0 && g.HoveredIdPreviousFrame != id)
3946
112
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
3947
360
}
3948
3949
ImGuiID ImGui::GetHoveredID()
3950
0
{
3951
0
    ImGuiContext& g = *GImGui;
3952
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
3953
0
}
3954
3955
// This is called by ItemAdd().
3956
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
3957
void ImGui::KeepAliveID(ImGuiID id)
3958
180k
{
3959
180k
    ImGuiContext& g = *GImGui;
3960
180k
    if (g.ActiveId == id)
3961
42
        g.ActiveIdIsAlive = id;
3962
180k
    if (g.ActiveIdPreviousFrame == id)
3963
39
        g.ActiveIdPreviousFrameIsAlive = true;
3964
180k
}
3965
3966
void ImGui::MarkItemEdited(ImGuiID id)
3967
0
{
3968
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
3969
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
3970
0
    ImGuiContext& g = *GImGui;
3971
0
    if (g.ActiveId == id || g.ActiveId == 0)
3972
0
    {
3973
0
        g.ActiveIdHasBeenEditedThisFrame = true;
3974
0
        g.ActiveIdHasBeenEditedBefore = true;
3975
0
    }
3976
3977
    // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
3978
    // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
3979
0
    IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id);
3980
3981
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
3982
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
3983
0
}
3984
3985
bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
3986
363
{
3987
    // An active popup disable hovering on other windows (apart from its own children)
3988
    // FIXME-OPT: This could be cached/stored within the window.
3989
363
    ImGuiContext& g = *GImGui;
3990
363
    if (g.NavWindow)
3991
305
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
3992
305
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
3993
0
            {
3994
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
3995
                // NB: The 'else' is important because Modal windows are also Popups.
3996
0
                bool want_inhibit = false;
3997
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
3998
0
                    want_inhibit = true;
3999
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4000
0
                    want_inhibit = true;
4001
4002
                // Inhibit hover unless the window is within the stack of our modal/popup
4003
0
                if (want_inhibit)
4004
0
                    if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4005
0
                        return false;
4006
0
            }
4007
4008
    // Filter by viewport
4009
363
    if (window->Viewport != g.MouseViewport)
4010
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4011
0
            return false;
4012
4013
363
    return true;
4014
363
}
4015
4016
// This is roughly matching the behavior of internal-facing ItemHoverable()
4017
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4018
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4019
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4020
0
{
4021
0
    ImGuiContext& g = *GImGui;
4022
0
    ImGuiWindow* window = g.CurrentWindow;
4023
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4024
0
    {
4025
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4026
0
            return false;
4027
0
        if (!IsItemFocused())
4028
0
            return false;
4029
0
    }
4030
0
    else
4031
0
    {
4032
        // Test for bounding box overlap, as updated as ItemAdd()
4033
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4034
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4035
0
            return false;
4036
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
4037
4038
        // Done with rectangle culling so we can perform heavier checks now
4039
        // Test if we are hovering the right window (our window could be behind another window)
4040
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4041
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4042
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4043
        // the test that has been running for a long while.
4044
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4045
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0)
4046
0
                return false;
4047
4048
        // Test if another item is active (e.g. being dragged)
4049
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4050
0
            if (g.ActiveId != 0 && g.ActiveId != g.LastItemData.ID && !g.ActiveIdAllowOverlap)
4051
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4052
0
                    return false;
4053
4054
        // Test if interactions on this window are blocked by an active popup or modal.
4055
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4056
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4057
0
            return false;
4058
4059
        // Test if the item is disabled
4060
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4061
0
            return false;
4062
4063
        // Special handling for calling after Begin() which represent the title bar or tab.
4064
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4065
        // will never be overwritten so we need to detect the case.
4066
0
        if (g.LastItemData.ID == window->MoveId && window->WriteAccessed)
4067
0
            return false;
4068
0
    }
4069
4070
    // Handle hover delay
4071
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4072
0
    float delay;
4073
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
4074
0
        delay = g.IO.HoverDelayNormal;
4075
0
    else if (flags & ImGuiHoveredFlags_DelayShort)
4076
0
        delay = g.IO.HoverDelayShort;
4077
0
    else
4078
0
        delay = 0.0f;
4079
0
    if (delay > 0.0f)
4080
0
    {
4081
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4082
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverDelayIdPreviousFrame != hover_delay_id))
4083
0
            g.HoverDelayTimer = 0.0f;
4084
0
        g.HoverDelayId = hover_delay_id;
4085
0
        return g.HoverDelayTimer >= delay;
4086
0
    }
4087
4088
0
    return true;
4089
0
}
4090
4091
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4092
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
4093
147k
{
4094
147k
    ImGuiContext& g = *GImGui;
4095
147k
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4096
337
        return false;
4097
4098
147k
    ImGuiWindow* window = g.CurrentWindow;
4099
147k
    if (g.HoveredWindow != window)
4100
145k
        return false;
4101
1.99k
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4102
33
        return false;
4103
1.96k
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4104
1.60k
        return false;
4105
4106
    // Done with rectangle culling so we can perform heavier checks now.
4107
360
    ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags);
4108
360
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4109
0
    {
4110
0
        g.HoveredIdDisabled = true;
4111
0
        return false;
4112
0
    }
4113
4114
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4115
    // hover test in widgets code. We could also decide to split this function is two.
4116
360
    if (id != 0)
4117
360
        SetHoveredID(id);
4118
4119
    // When disabled we'll return false but still set HoveredId
4120
360
    if (item_flags & ImGuiItemFlags_Disabled)
4121
0
    {
4122
        // Release active id if turning disabled
4123
0
        if (g.ActiveId == id)
4124
0
            ClearActiveID();
4125
0
        g.HoveredIdDisabled = true;
4126
0
        return false;
4127
0
    }
4128
4129
360
    if (id != 0)
4130
360
    {
4131
        // [DEBUG] Item Picker tool!
4132
        // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
4133
        // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
4134
        // items if we performed the test in ItemAdd(), but that would incur a small runtime cost.
4135
360
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4136
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4137
360
        if (g.DebugItemPickerBreakId == id)
4138
0
            IM_DEBUG_BREAK();
4139
360
    }
4140
4141
360
    if (g.NavDisableMouseHover)
4142
62
        return false;
4143
4144
298
    return true;
4145
360
}
4146
4147
// FIXME: This is inlined/duplicated in ItemAdd()
4148
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4149
0
{
4150
0
    ImGuiContext& g = *GImGui;
4151
0
    ImGuiWindow* window = g.CurrentWindow;
4152
0
    if (!bb.Overlaps(window->ClipRect))
4153
0
        if (id == 0 || (id != g.ActiveId && id != g.NavId))
4154
0
            if (!g.LogEnabled)
4155
0
                return true;
4156
0
    return false;
4157
0
}
4158
4159
// This is also inlined in ItemAdd()
4160
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4161
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4162
107k
{
4163
107k
    ImGuiContext& g = *GImGui;
4164
107k
    g.LastItemData.ID = item_id;
4165
107k
    g.LastItemData.InFlags = in_flags;
4166
107k
    g.LastItemData.StatusFlags = item_flags;
4167
107k
    g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4168
107k
}
4169
4170
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4171
0
{
4172
0
    if (wrap_pos_x < 0.0f)
4173
0
        return 0.0f;
4174
4175
0
    ImGuiContext& g = *GImGui;
4176
0
    ImGuiWindow* window = g.CurrentWindow;
4177
0
    if (wrap_pos_x == 0.0f)
4178
0
    {
4179
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4180
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4181
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4182
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4183
        //else
4184
0
        wrap_pos_x = window->WorkRect.Max.x;
4185
0
    }
4186
0
    else if (wrap_pos_x > 0.0f)
4187
0
    {
4188
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4189
0
    }
4190
4191
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4192
0
}
4193
4194
// IM_ALLOC() == ImGui::MemAlloc()
4195
void* ImGui::MemAlloc(size_t size)
4196
1.25k
{
4197
1.25k
    if (ImGuiContext* ctx = GImGui)
4198
1.24k
        ctx->IO.MetricsActiveAllocations++;
4199
1.25k
    return (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4200
1.25k
}
4201
4202
// IM_FREE() == ImGui::MemFree()
4203
void ImGui::MemFree(void* ptr)
4204
1.20k
{
4205
1.20k
    if (ptr)
4206
1.19k
        if (ImGuiContext* ctx = GImGui)
4207
1.19k
            ctx->IO.MetricsActiveAllocations--;
4208
1.20k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4209
1.20k
}
4210
4211
const char* ImGui::GetClipboardText()
4212
0
{
4213
0
    ImGuiContext& g = *GImGui;
4214
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4215
0
}
4216
4217
void ImGui::SetClipboardText(const char* text)
4218
0
{
4219
0
    ImGuiContext& g = *GImGui;
4220
0
    if (g.IO.SetClipboardTextFn)
4221
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4222
0
}
4223
4224
const char* ImGui::GetVersion()
4225
0
{
4226
0
    return IMGUI_VERSION;
4227
0
}
4228
4229
ImGuiIO& ImGui::GetIO()
4230
133k
{
4231
133k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4232
133k
    return GImGui->IO;
4233
133k
}
4234
4235
ImGuiPlatformIO& ImGui::GetPlatformIO()
4236
0
{
4237
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4238
0
    return GImGui->PlatformIO;
4239
0
}
4240
4241
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4242
ImDrawData* ImGui::GetDrawData()
4243
35.9k
{
4244
35.9k
    ImGuiContext& g = *GImGui;
4245
35.9k
    ImGuiViewportP* viewport = g.Viewports[0];
4246
35.9k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4247
35.9k
}
4248
4249
double ImGui::GetTime()
4250
2
{
4251
2
    return GImGui->Time;
4252
2
}
4253
4254
int ImGui::GetFrameCount()
4255
0
{
4256
0
    return GImGui->FrameCount;
4257
0
}
4258
4259
static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4260
0
{
4261
    // Create the draw list on demand, because they are not frequently used for all viewports
4262
0
    ImGuiContext& g = *GImGui;
4263
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->DrawLists));
4264
0
    ImDrawList* draw_list = viewport->DrawLists[drawlist_no];
4265
0
    if (draw_list == NULL)
4266
0
    {
4267
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4268
0
        draw_list->_OwnerName = drawlist_name;
4269
0
        viewport->DrawLists[drawlist_no] = draw_list;
4270
0
    }
4271
4272
    // Our ImDrawList system requires that there is always a command
4273
0
    if (viewport->DrawListsLastFrame[drawlist_no] != g.FrameCount)
4274
0
    {
4275
0
        draw_list->_ResetForNewFrame();
4276
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4277
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4278
0
        viewport->DrawListsLastFrame[drawlist_no] = g.FrameCount;
4279
0
    }
4280
0
    return draw_list;
4281
0
}
4282
4283
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4284
0
{
4285
0
    return GetViewportDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4286
0
}
4287
4288
ImDrawList* ImGui::GetBackgroundDrawList()
4289
0
{
4290
0
    ImGuiContext& g = *GImGui;
4291
0
    return GetBackgroundDrawList(g.CurrentWindow->Viewport);
4292
0
}
4293
4294
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4295
0
{
4296
0
    return GetViewportDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4297
0
}
4298
4299
ImDrawList* ImGui::GetForegroundDrawList()
4300
0
{
4301
0
    ImGuiContext& g = *GImGui;
4302
0
    return GetForegroundDrawList(g.CurrentWindow->Viewport);
4303
0
}
4304
4305
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4306
0
{
4307
0
    return &GImGui->DrawListSharedData;
4308
0
}
4309
4310
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4311
3
{
4312
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4313
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4314
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4315
3
    ImGuiContext& g = *GImGui;
4316
3
    FocusWindow(window);
4317
3
    SetActiveID(window->MoveId, window);
4318
3
    g.NavDisableHighlight = true;
4319
3
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4320
3
    g.ActiveIdNoClearOnFocusLoss = true;
4321
3
    SetActiveIdUsingAllKeyboardKeys();
4322
4323
3
    bool can_move_window = true;
4324
3
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4325
0
        can_move_window = false;
4326
3
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4327
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4328
0
            can_move_window = false;
4329
3
    if (can_move_window)
4330
3
        g.MovingWindow = window;
4331
3
}
4332
4333
// We use 'undock_floating_node == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4334
// - undock_floating_node == true: when dragging from a floating node within a hierarchy, always undock the node.
4335
// - undock_floating_node == false: when dragging from a floating node within a hierarchy, move root window.
4336
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock_floating_node)
4337
3
{
4338
3
    ImGuiContext& g = *GImGui;
4339
3
    bool can_undock_node = false;
4340
3
    if (node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0)
4341
0
    {
4342
        // Can undock if:
4343
        // - part of a floating node hierarchy with more than one visible node (if only one is visible, we'll just move the whole hierarchy)
4344
        // - part of a dockspace node hierarchy (trivia: undocking from a fixed/central node will create a new node and copy windows)
4345
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4346
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4347
0
            if (undock_floating_node || root_node->IsDockSpace())
4348
0
                can_undock_node = true;
4349
0
    }
4350
4351
3
    const bool clicked = IsMouseClicked(0);
4352
3
    const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f);
4353
3
    if (can_undock_node && dragging)
4354
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4355
3
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4356
3
        StartMouseMovingWindow(window);
4357
3
}
4358
4359
// Handle mouse moving window
4360
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4361
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4362
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4363
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4364
void ImGui::UpdateMouseMovingWindowNewFrame()
4365
35.9k
{
4366
35.9k
    ImGuiContext& g = *GImGui;
4367
35.9k
    if (g.MovingWindow != NULL)
4368
18
    {
4369
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4370
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4371
18
        KeepAliveID(g.ActiveId);
4372
18
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4373
18
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4374
4375
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4376
18
        const bool window_disappared = ((!moving_window->WasActive && !moving_window->Active) || moving_window->Viewport == NULL);
4377
18
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4378
15
        {
4379
15
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4380
15
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4381
8
            {
4382
8
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4383
8
                if (moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4384
0
                {
4385
0
                    moving_window->Viewport->Pos = pos;
4386
0
                    moving_window->Viewport->UpdateWorkRect();
4387
0
                }
4388
8
            }
4389
15
            FocusWindow(g.MovingWindow);
4390
15
        }
4391
3
        else
4392
3
        {
4393
3
            if (!window_disappared)
4394
3
            {
4395
                // Try to merge the window back into the main viewport.
4396
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4397
3
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4398
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4399
4400
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4401
3
                if (!IsDragDropPayloadBeingAccepted())
4402
3
                    g.MouseViewport = moving_window->Viewport;
4403
4404
                // Clear the NoInput window flag set by the Viewport system
4405
3
                moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs; // FIXME-VIEWPORT: Test engine managed to crash here because Viewport was NULL.
4406
3
            }
4407
4408
3
            g.MovingWindow = NULL;
4409
3
            ClearActiveID();
4410
3
        }
4411
18
    }
4412
35.8k
    else
4413
35.8k
    {
4414
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4415
35.8k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4416
0
        {
4417
0
            KeepAliveID(g.ActiveId);
4418
0
            if (!g.IO.MouseDown[0])
4419
0
                ClearActiveID();
4420
0
        }
4421
35.8k
    }
4422
35.9k
}
4423
4424
// Initiate moving window when clicking on empty space or title bar.
4425
// Handle left-click and right-click focus.
4426
void ImGui::UpdateMouseMovingWindowEndFrame()
4427
35.9k
{
4428
35.9k
    ImGuiContext& g = *GImGui;
4429
35.9k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4430
382
        return;
4431
4432
    // Unless we just made a window/popup appear
4433
35.5k
    if (g.NavWindow && g.NavWindow->Appearing)
4434
1
        return;
4435
4436
    // Click on empty space to focus window and start moving
4437
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4438
35.5k
    if (g.IO.MouseClicked[0])
4439
660
    {
4440
        // Handle the edge case of a popup being closed while clicking in its empty space.
4441
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4442
660
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4443
660
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4444
4445
660
        if (root_window != NULL && !is_closed_popup)
4446
0
        {
4447
0
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4448
4449
            // Cancel moving if clicked outside of title bar
4450
0
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4451
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4452
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4453
0
                        g.MovingWindow = NULL;
4454
4455
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4456
0
            if (g.HoveredIdDisabled)
4457
0
                g.MovingWindow = NULL;
4458
0
        }
4459
660
        else if (root_window == NULL && g.NavWindow != NULL)
4460
520
        {
4461
            // Clicking on void disable focus
4462
520
            FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4463
520
        }
4464
660
    }
4465
4466
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4467
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4468
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4469
35.5k
    if (g.IO.MouseClicked[1])
4470
201
    {
4471
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4472
        // This is where we can trim the popup stack.
4473
201
        ImGuiWindow* modal = GetTopMostPopupModal();
4474
201
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4475
201
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4476
201
    }
4477
35.5k
}
4478
4479
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4480
// Need to keep in sync with SetWindowPos()
4481
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4482
0
{
4483
0
    window->Pos += delta;
4484
0
    window->ClipRect.Translate(delta);
4485
0
    window->OuterRectClipped.Translate(delta);
4486
0
    window->InnerRect.Translate(delta);
4487
0
    window->DC.CursorPos += delta;
4488
0
    window->DC.CursorStartPos += delta;
4489
0
    window->DC.CursorMaxPos += delta;
4490
0
    window->DC.IdealMaxPos += delta;
4491
0
}
4492
4493
static void ScaleWindow(ImGuiWindow* window, float scale)
4494
0
{
4495
0
    ImVec2 origin = window->Viewport->Pos;
4496
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4497
0
    window->Size = ImFloor(window->Size * scale);
4498
0
    window->SizeFull = ImFloor(window->SizeFull * scale);
4499
0
    window->ContentSize = ImFloor(window->ContentSize * scale);
4500
0
}
4501
4502
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4503
143k
{
4504
143k
    return (window->Active) && (!window->Hidden);
4505
143k
}
4506
4507
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4508
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4509
35.9k
{
4510
35.9k
    ImGuiContext& g = *GImGui;
4511
35.9k
    ImGuiIO& io = g.IO;
4512
35.9k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4513
4514
    // Find the window hovered by mouse:
4515
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4516
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4517
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4518
35.9k
    bool clear_hovered_windows = false;
4519
35.9k
    FindHoveredWindow();
4520
35.9k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4521
4522
    // Modal windows prevents mouse from hovering behind them.
4523
35.9k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4524
35.9k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4525
0
        clear_hovered_windows = true;
4526
4527
    // Disabled mouse?
4528
35.9k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4529
0
        clear_hovered_windows = true;
4530
4531
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4532
    // won't report hovering nor request capture even while dragging over our windows afterward.
4533
35.9k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4534
35.9k
    const bool has_open_modal = (modal_window != NULL);
4535
35.9k
    int mouse_earliest_down = -1;
4536
35.9k
    bool mouse_any_down = false;
4537
215k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4538
179k
    {
4539
179k
        if (io.MouseClicked[i])
4540
1.23k
        {
4541
1.23k
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4542
1.23k
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4543
1.23k
        }
4544
179k
        mouse_any_down |= io.MouseDown[i];
4545
179k
        if (io.MouseDown[i])
4546
5.56k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4547
3.31k
                mouse_earliest_down = i;
4548
179k
    }
4549
35.9k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4550
35.9k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4551
4552
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4553
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4554
35.9k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4555
35.9k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4556
2.83k
        clear_hovered_windows = true;
4557
4558
35.9k
    if (clear_hovered_windows)
4559
2.83k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4560
4561
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4562
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4563
35.9k
    if (g.WantCaptureMouseNextFrame != -1)
4564
0
    {
4565
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4566
0
    }
4567
35.9k
    else
4568
35.9k
    {
4569
35.9k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4570
35.9k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4571
35.9k
    }
4572
4573
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4574
35.9k
    if (g.WantCaptureKeyboardNextFrame != -1)
4575
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4576
35.9k
    else
4577
35.9k
        io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4578
35.9k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4579
28.2k
        io.WantCaptureKeyboard = true;
4580
4581
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4582
35.9k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4583
35.9k
}
4584
4585
void ImGui::NewFrame()
4586
35.9k
{
4587
35.9k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4588
35.9k
    ImGuiContext& g = *GImGui;
4589
4590
    // Remove pending delete hooks before frame start.
4591
    // This deferred removal avoid issues of removal while iterating the hook vector
4592
35.9k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4593
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4594
0
            g.Hooks.erase(&g.Hooks[n]);
4595
4596
35.9k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4597
4598
    // Check and assert for various common IO and Configuration mistakes
4599
35.9k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4600
35.9k
    ErrorCheckNewFrameSanityChecks();
4601
35.9k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4602
4603
    // Load settings on first frame, save settings when modified (after a delay)
4604
35.9k
    UpdateSettings();
4605
4606
35.9k
    g.Time += g.IO.DeltaTime;
4607
35.9k
    g.WithinFrameScope = true;
4608
35.9k
    g.FrameCount += 1;
4609
35.9k
    g.TooltipOverrideCount = 0;
4610
35.9k
    g.WindowsActiveCount = 0;
4611
35.9k
    g.MenusIdSubmittedThisFrame.resize(0);
4612
4613
    // Calculate frame-rate for the user, as a purely luxurious feature
4614
35.9k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4615
35.9k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4616
35.9k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4617
35.9k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4618
35.9k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4619
4620
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4621
35.9k
    g.InputEventsTrail.resize(0);
4622
35.9k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4623
4624
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4625
35.9k
    UpdateViewportsNewFrame();
4626
4627
    // Setup current font and draw list shared data
4628
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4629
35.9k
    g.IO.Fonts->Locked = true;
4630
35.9k
    SetCurrentFont(GetDefaultFont());
4631
35.9k
    IM_ASSERT(g.Font->IsLoaded());
4632
35.9k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4633
71.8k
    for (int n = 0; n < g.Viewports.Size; n++)
4634
35.9k
        virtual_space.Add(g.Viewports[n]->GetMainRect());
4635
35.9k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4636
35.9k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4637
35.9k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4638
35.9k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4639
35.9k
    if (g.Style.AntiAliasedLines)
4640
35.9k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4641
35.9k
    if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4642
35.9k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4643
35.9k
    if (g.Style.AntiAliasedFill)
4644
35.9k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4645
35.9k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4646
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4647
4648
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4649
71.8k
    for (int n = 0; n < g.Viewports.Size; n++)
4650
35.9k
    {
4651
35.9k
        ImGuiViewportP* viewport = g.Viewports[n];
4652
35.9k
        viewport->DrawData = NULL;
4653
35.9k
        viewport->DrawDataP.Clear();
4654
35.9k
    }
4655
4656
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4657
35.9k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4658
18
        KeepAliveID(g.DragDropPayload.SourceId);
4659
4660
    // Update HoveredId data
4661
35.9k
    if (!g.HoveredIdPreviousFrame)
4662
35.5k
        g.HoveredIdTimer = 0.0f;
4663
35.9k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4664
35.5k
        g.HoveredIdNotActiveTimer = 0.0f;
4665
35.9k
    if (g.HoveredId)
4666
360
        g.HoveredIdTimer += g.IO.DeltaTime;
4667
35.9k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4668
354
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4669
35.9k
    g.HoveredIdPreviousFrame = g.HoveredId;
4670
35.9k
    g.HoveredId = 0;
4671
35.9k
    g.HoveredIdAllowOverlap = false;
4672
35.9k
    g.HoveredIdDisabled = false;
4673
4674
    // Clear ActiveID if the item is not alive anymore.
4675
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4676
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4677
35.9k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4678
0
    {
4679
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4680
0
        ClearActiveID();
4681
0
    }
4682
4683
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4684
35.9k
    if (g.ActiveId)
4685
25
        g.ActiveIdTimer += g.IO.DeltaTime;
4686
35.9k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4687
35.9k
    g.ActiveIdPreviousFrame = g.ActiveId;
4688
35.9k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4689
35.9k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4690
35.9k
    g.ActiveIdIsAlive = 0;
4691
35.9k
    g.ActiveIdHasBeenEditedThisFrame = false;
4692
35.9k
    g.ActiveIdPreviousFrameIsAlive = false;
4693
35.9k
    g.ActiveIdIsJustActivated = false;
4694
35.9k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4695
0
        g.TempInputId = 0;
4696
35.9k
    if (g.ActiveId == 0)
4697
35.8k
    {
4698
35.8k
        g.ActiveIdUsingNavDirMask = 0x00;
4699
35.8k
        g.ActiveIdUsingAllKeyboardKeys = false;
4700
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4701
        g.ActiveIdUsingNavInputMask = 0x00;
4702
#endif
4703
35.8k
    }
4704
4705
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4706
    if (g.ActiveId == 0)
4707
        g.ActiveIdUsingNavInputMask = 0;
4708
    else if (g.ActiveIdUsingNavInputMask != 0)
4709
    {
4710
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4711
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4712
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4713
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4714
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4715
            IM_ASSERT(0); // Other values unsupported
4716
    }
4717
#endif
4718
4719
    // Update hover delay for IsItemHovered() with delays and tooltips
4720
35.9k
    g.HoverDelayIdPreviousFrame = g.HoverDelayId;
4721
35.9k
    if (g.HoverDelayId != 0)
4722
0
    {
4723
        //if (g.IO.MouseDelta.x == 0.0f && g.IO.MouseDelta.y == 0.0f) // Need design/flags
4724
0
        g.HoverDelayTimer += g.IO.DeltaTime;
4725
0
        g.HoverDelayClearTimer = 0.0f;
4726
0
        g.HoverDelayId = 0;
4727
0
    }
4728
35.9k
    else if (g.HoverDelayTimer > 0.0f)
4729
0
    {
4730
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4731
0
        g.HoverDelayClearTimer += g.IO.DeltaTime;
4732
0
        if (g.HoverDelayClearTimer >= ImMax(0.20f, g.IO.DeltaTime * 2.0f)) // ~6 frames at 30 Hz + allow for low framerate
4733
0
            g.HoverDelayTimer = g.HoverDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4734
0
    }
4735
4736
    // Drag and drop
4737
35.9k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4738
35.9k
    g.DragDropAcceptIdCurr = 0;
4739
35.9k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4740
35.9k
    g.DragDropWithinSource = false;
4741
35.9k
    g.DragDropWithinTarget = false;
4742
35.9k
    g.DragDropHoldJustPressedId = 0;
4743
4744
    // Close popups on focus lost (currently wip/opt-in)
4745
    //if (g.IO.AppFocusLost)
4746
    //    ClosePopupsExceptModals();
4747
4748
    // Update keyboard input state
4749
35.9k
    UpdateKeyboardInputs();
4750
4751
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4752
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4753
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4754
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4755
4756
    // Update gamepad/keyboard navigation
4757
35.9k
    NavUpdate();
4758
4759
    // Update mouse input state
4760
35.9k
    UpdateMouseInputs();
4761
4762
    // Undocking
4763
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4764
35.9k
    DockContextNewFrameUpdateUndocking(&g);
4765
4766
    // Find hovered window
4767
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4768
35.9k
    UpdateHoveredWindowAndCaptureFlags();
4769
4770
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4771
35.9k
    UpdateMouseMovingWindowNewFrame();
4772
4773
    // Background darkening/whitening
4774
35.9k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4775
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4776
35.9k
    else
4777
35.9k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4778
4779
35.9k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
4780
35.9k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4781
4782
    // Platform IME data: reset for the frame
4783
35.9k
    g.PlatformImeDataPrev = g.PlatformImeData;
4784
35.9k
    g.PlatformImeData.WantVisible = false;
4785
4786
    // Mouse wheel scrolling, scale
4787
35.9k
    UpdateMouseWheel();
4788
4789
    // Mark all windows as not visible and compact unused memory.
4790
35.9k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4791
35.9k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4792
143k
    for (int i = 0; i != g.Windows.Size; i++)
4793
107k
    {
4794
107k
        ImGuiWindow* window = g.Windows[i];
4795
107k
        window->WasActive = window->Active;
4796
107k
        window->Active = false;
4797
107k
        window->WriteAccessed = false;
4798
107k
        window->BeginCountPreviousFrame = window->BeginCount;
4799
107k
        window->BeginCount = 0;
4800
4801
        // Garbage collect transient buffers of recently unused windows
4802
107k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4803
0
            GcCompactTransientWindowBuffers(window);
4804
107k
    }
4805
4806
    // Garbage collect transient buffers of recently unused tables
4807
35.9k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4808
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4809
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4810
35.9k
    for (int i = 0; i < g.TablesTempData.Size; i++)
4811
0
        if (g.TablesTempData[i].LastTimeActive >= 0.0f && g.TablesTempData[i].LastTimeActive < memory_compact_start_time)
4812
0
            TableGcCompactTransientBuffers(&g.TablesTempData[i]);
4813
35.9k
    if (g.GcCompactAll)
4814
0
        GcCompactTransientMiscBuffers();
4815
35.9k
    g.GcCompactAll = false;
4816
4817
    // Closing the focused window restore focus to the first active root window in descending z-order
4818
35.9k
    if (g.NavWindow && !g.NavWindow->WasActive)
4819
0
        FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
4820
4821
    // No window should be open at the beginning of the frame.
4822
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4823
35.9k
    g.CurrentWindowStack.resize(0);
4824
35.9k
    g.BeginPopupStack.resize(0);
4825
35.9k
    g.ItemFlagsStack.resize(0);
4826
35.9k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
4827
35.9k
    g.GroupStack.resize(0);
4828
4829
    // Docking
4830
35.9k
    DockContextNewFrameUpdateDocking(&g);
4831
4832
    // [DEBUG] Update debug features
4833
35.9k
    UpdateDebugToolItemPicker();
4834
35.9k
    UpdateDebugToolStackQueries();
4835
35.9k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
4836
0
        g.DebugLocateId = 0;
4837
35.9k
    if (g.DebugLogClipperAutoDisableFrames > 0 && --g.DebugLogClipperAutoDisableFrames == 0)
4838
0
    {
4839
0
        DebugLog("(Auto-disabled ImGuiDebugLogFlags_EventClipper to avoid spamming)\n");
4840
0
        g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
4841
0
    }
4842
4843
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
4844
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
4845
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
4846
35.9k
    g.WithinFrameScopeWithImplicitWindow = true;
4847
35.9k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
4848
35.9k
    Begin("Debug##Default");
4849
35.9k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
4850
4851
    // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
4852
    // allowing to validate correct Begin/End behavior in user code.
4853
35.9k
    if (g.IO.ConfigDebugBeginReturnValueLoop)
4854
0
        g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
4855
35.9k
    else
4856
35.9k
        g.DebugBeginReturnValueCullDepth = -1;
4857
4858
35.9k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
4859
35.9k
}
4860
4861
// FIXME: Add a more explicit sort order in the window structure.
4862
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
4863
0
{
4864
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
4865
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
4866
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
4867
0
        return d;
4868
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
4869
0
        return d;
4870
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
4871
0
}
4872
4873
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
4874
107k
{
4875
107k
    out_sorted_windows->push_back(window);
4876
107k
    if (window->Active)
4877
71.8k
    {
4878
71.8k
        int count = window->DC.ChildWindows.Size;
4879
71.8k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
4880
107k
        for (int i = 0; i < count; i++)
4881
35.9k
        {
4882
35.9k
            ImGuiWindow* child = window->DC.ChildWindows[i];
4883
35.9k
            if (child->Active)
4884
35.9k
                AddWindowToSortBuffer(out_sorted_windows, child);
4885
35.9k
        }
4886
71.8k
    }
4887
107k
}
4888
4889
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
4890
61.9k
{
4891
61.9k
    if (draw_list->CmdBuffer.Size == 0)
4892
0
        return;
4893
61.9k
    if (draw_list->CmdBuffer.Size == 1 && draw_list->CmdBuffer[0].ElemCount == 0 && draw_list->CmdBuffer[0].UserCallback == NULL)
4894
763
        return;
4895
4896
    // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
4897
    // May trigger for you if you are using PrimXXX functions incorrectly.
4898
61.2k
    IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
4899
61.2k
    IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
4900
61.2k
    if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
4901
61.2k
        IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
4902
4903
    // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
4904
    // If this assert triggers because you are drawing lots of stuff manually:
4905
    // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
4906
    //   Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents.
4907
    // - If you want large meshes with more than 64K vertices, you can either:
4908
    //   (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
4909
    //       Most example backends already support this from 1.71. Pre-1.71 backends won't.
4910
    //       Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
4911
    //   (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
4912
    //       Most example backends already support this. For example, the OpenGL example code detect index size at compile-time:
4913
    //         glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
4914
    //       Your own engine or render API may use different parameters or function calls to specify index sizes.
4915
    //       2 and 4 bytes indices are generally supported by most graphics API.
4916
    // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
4917
    //   the 64K limit to split your draw commands in multiple draw lists.
4918
61.2k
    if (sizeof(ImDrawIdx) == 2)
4919
61.2k
        IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
4920
4921
61.2k
    out_list->push_back(draw_list);
4922
61.2k
}
4923
4924
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
4925
61.9k
{
4926
61.9k
    ImGuiContext& g = *GImGui;
4927
61.9k
    ImGuiViewportP* viewport = window->Viewport;
4928
61.9k
    g.IO.MetricsRenderWindows++;
4929
61.9k
    if (window->Flags & ImGuiWindowFlags_DockNodeHost)
4930
0
        window->DrawList->ChannelsMerge();
4931
61.9k
    AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[layer], window->DrawList);
4932
97.8k
    for (int i = 0; i < window->DC.ChildWindows.Size; i++)
4933
35.9k
    {
4934
35.9k
        ImGuiWindow* child = window->DC.ChildWindows[i];
4935
35.9k
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
4936
26.0k
            AddWindowToDrawData(child, layer);
4937
35.9k
    }
4938
61.9k
}
4939
4940
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
4941
35.9k
{
4942
35.9k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
4943
35.9k
}
4944
4945
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
4946
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
4947
35.9k
{
4948
35.9k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
4949
35.9k
}
4950
4951
void ImDrawDataBuilder::FlattenIntoSingleLayer()
4952
35.9k
{
4953
35.9k
    int n = Layers[0].Size;
4954
35.9k
    int size = n;
4955
71.8k
    for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
4956
35.9k
        size += Layers[i].Size;
4957
35.9k
    Layers[0].resize(size);
4958
71.8k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
4959
35.9k
    {
4960
35.9k
        ImVector<ImDrawList*>& layer = Layers[layer_n];
4961
35.9k
        if (layer.empty())
4962
35.9k
            continue;
4963
0
        memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
4964
0
        n += layer.Size;
4965
0
        layer.resize(0);
4966
0
    }
4967
35.9k
}
4968
4969
static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)
4970
35.9k
{
4971
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
4972
    // and to allow applications/backends to easily skip rendering.
4973
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
4974
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
4975
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
4976
35.9k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
4977
4978
35.9k
    ImGuiIO& io = ImGui::GetIO();
4979
35.9k
    ImDrawData* draw_data = &viewport->DrawDataP;
4980
35.9k
    viewport->DrawData = draw_data; // Make publicly accessible
4981
35.9k
    draw_data->Valid = true;
4982
35.9k
    draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
4983
35.9k
    draw_data->CmdListsCount = draw_lists->Size;
4984
35.9k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
4985
35.9k
    draw_data->DisplayPos = viewport->Pos;
4986
35.9k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
4987
35.9k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
4988
35.9k
    draw_data->OwnerViewport = viewport;
4989
97.1k
    for (int n = 0; n < draw_lists->Size; n++)
4990
61.2k
    {
4991
61.2k
        ImDrawList* draw_list = draw_lists->Data[n];
4992
61.2k
        draw_list->_PopUnusedDrawCmd();
4993
61.2k
        draw_data->TotalVtxCount += draw_list->VtxBuffer.Size;
4994
61.2k
        draw_data->TotalIdxCount += draw_list->IdxBuffer.Size;
4995
61.2k
    }
4996
35.9k
}
4997
4998
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
4999
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5000
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5001
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5002
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5003
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5004
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5005
215k
{
5006
215k
    ImGuiWindow* window = GetCurrentWindow();
5007
215k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5008
215k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5009
215k
}
5010
5011
void ImGui::PopClipRect()
5012
107k
{
5013
107k
    ImGuiWindow* window = GetCurrentWindow();
5014
107k
    window->DrawList->PopClipRect();
5015
107k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5016
107k
}
5017
5018
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5019
0
{
5020
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5021
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5022
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5023
0
    return window;
5024
0
}
5025
5026
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5027
0
{
5028
0
    if ((col & IM_COL32_A_MASK) == 0)
5029
0
        return;
5030
5031
0
    ImGuiViewportP* viewport = window->Viewport;
5032
0
    ImRect viewport_rect = viewport->GetMainRect();
5033
5034
    // Draw behind window by moving the draw command at the FRONT of the draw list
5035
0
    {
5036
        // We've already called AddWindowToDrawData() which called DrawList->ChannelsMerge() on DockNodeHost windows,
5037
        // and draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5038
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5039
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5040
0
        if (draw_list->CmdBuffer.Size == 0)
5041
0
            draw_list->AddDrawCmd();
5042
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // Ensure ImDrawCmd are not merged
5043
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5044
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
5045
0
        IM_ASSERT(cmd.ElemCount == 6);
5046
0
        draw_list->CmdBuffer.pop_back();
5047
0
        draw_list->CmdBuffer.push_front(cmd);
5048
0
        draw_list->PopClipRect();
5049
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5050
0
    }
5051
5052
    // Draw over sibling docking nodes in a same docking tree
5053
0
    if (window->RootWindow->DockIsActive)
5054
0
    {
5055
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5056
0
        if (draw_list->CmdBuffer.Size == 0)
5057
0
            draw_list->AddDrawCmd();
5058
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5059
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5060
0
        draw_list->PopClipRect();
5061
0
    }
5062
0
}
5063
5064
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5065
0
{
5066
0
    ImGuiContext& g = *GImGui;
5067
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
5068
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5069
0
    {
5070
0
        ImGuiWindow* window = g.Windows[i];
5071
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
5072
0
            continue;
5073
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
5074
0
            break;
5075
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5076
0
            bottom_most_visible_window = window;
5077
0
    }
5078
0
    return bottom_most_visible_window;
5079
0
}
5080
5081
static void ImGui::RenderDimmedBackgrounds()
5082
35.9k
{
5083
35.9k
    ImGuiContext& g = *GImGui;
5084
35.9k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5085
35.9k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5086
35.9k
        return;
5087
0
    const bool dim_bg_for_modal = (modal_window != NULL);
5088
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5089
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5090
0
        return;
5091
5092
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5093
0
    if (dim_bg_for_modal)
5094
0
    {
5095
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5096
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5097
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(ImGuiCol_ModalWindowDimBg, g.DimBgRatio));
5098
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5099
0
    }
5100
0
    else if (dim_bg_for_window_list)
5101
0
    {
5102
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5103
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5104
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5105
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5106
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5107
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5108
5109
        // Draw border around CTRL+Tab target window
5110
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5111
0
        ImGuiViewport* viewport = window->Viewport;
5112
0
        float distance = g.FontSize;
5113
0
        ImRect bb = window->Rect();
5114
0
        bb.Expand(distance);
5115
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5116
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5117
0
        if (window->DrawList->CmdBuffer.Size == 0)
5118
0
            window->DrawList->AddDrawCmd();
5119
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5120
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5121
0
        window->DrawList->PopClipRect();
5122
0
    }
5123
5124
    // Draw dimming background on _other_ viewports than the ones our windows are in
5125
0
    for (int viewport_n = 0; viewport_n < g.Viewports.Size; viewport_n++)
5126
0
    {
5127
0
        ImGuiViewportP* viewport = g.Viewports[viewport_n];
5128
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5129
0
            continue;
5130
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5131
0
            continue;
5132
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5133
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5134
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5135
0
    }
5136
0
}
5137
5138
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5139
void ImGui::EndFrame()
5140
71.8k
{
5141
71.8k
    ImGuiContext& g = *GImGui;
5142
71.8k
    IM_ASSERT(g.Initialized);
5143
5144
    // Don't process EndFrame() multiple times.
5145
71.8k
    if (g.FrameCountEnded == g.FrameCount)
5146
35.9k
        return;
5147
35.9k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5148
5149
35.9k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5150
5151
35.9k
    ErrorCheckEndFrameSanityChecks();
5152
5153
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5154
35.9k
    ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5155
35.9k
    if (g.IO.SetPlatformImeDataFn && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5156
0
    {
5157
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5158
0
        IMGUI_DEBUG_LOG_IO("[io] Calling io.SetPlatformImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5159
0
        if (viewport == NULL)
5160
0
            viewport = GetMainViewport();
5161
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5162
        if (viewport->PlatformHandleRaw == NULL && g.IO.ImeWindowHandle != NULL)
5163
        {
5164
            viewport->PlatformHandleRaw = g.IO.ImeWindowHandle;
5165
            g.IO.SetPlatformImeDataFn(viewport, ime_data);
5166
            viewport->PlatformHandleRaw = NULL;
5167
        }
5168
        else
5169
#endif
5170
0
        {
5171
0
            g.IO.SetPlatformImeDataFn(viewport, ime_data);
5172
0
        }
5173
0
    }
5174
5175
    // Hide implicit/fallback "Debug" window if it hasn't been used
5176
35.9k
    g.WithinFrameScopeWithImplicitWindow = false;
5177
35.9k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5178
35.9k
        g.CurrentWindow->Active = false;
5179
35.9k
    End();
5180
5181
    // Update navigation: CTRL+Tab, wrap-around requests
5182
35.9k
    NavEndFrame();
5183
5184
    // Update docking
5185
35.9k
    DockContextEndFrame(&g);
5186
5187
35.9k
    SetCurrentViewport(NULL, NULL);
5188
5189
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5190
35.9k
    if (g.DragDropActive)
5191
24
    {
5192
24
        bool is_delivered = g.DragDropPayload.Delivery;
5193
24
        bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
5194
24
        if (is_delivered || is_elapsed)
5195
3
            ClearDragDrop();
5196
24
    }
5197
5198
    // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5199
35.9k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5200
0
    {
5201
0
        g.DragDropWithinSource = true;
5202
0
        SetTooltip("...");
5203
0
        g.DragDropWithinSource = false;
5204
0
    }
5205
5206
    // End frame
5207
35.9k
    g.WithinFrameScope = false;
5208
35.9k
    g.FrameCountEnded = g.FrameCount;
5209
5210
    // Initiate moving window + handle left-click and right-click focus
5211
35.9k
    UpdateMouseMovingWindowEndFrame();
5212
5213
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5214
35.9k
    UpdateViewportsEndFrame();
5215
5216
    // Sort the window list so that all child windows are after their parent
5217
    // We cannot do that on FocusWindow() because children may not exist yet
5218
35.9k
    g.WindowsTempSortBuffer.resize(0);
5219
35.9k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5220
143k
    for (int i = 0; i != g.Windows.Size; i++)
5221
107k
    {
5222
107k
        ImGuiWindow* window = g.Windows[i];
5223
107k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5224
35.9k
            continue;
5225
71.8k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5226
71.8k
    }
5227
5228
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5229
35.9k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5230
35.9k
    g.Windows.swap(g.WindowsTempSortBuffer);
5231
35.9k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5232
5233
    // Unlock font atlas
5234
35.9k
    g.IO.Fonts->Locked = false;
5235
5236
    // Clear Input data for next frame
5237
35.9k
    g.IO.AppFocusLost = false;
5238
35.9k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5239
35.9k
    g.IO.InputQueueCharacters.resize(0);
5240
5241
35.9k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5242
35.9k
}
5243
5244
// Prepare the data for rendering so you can call GetDrawData()
5245
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5246
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5247
void ImGui::Render()
5248
35.9k
{
5249
35.9k
    ImGuiContext& g = *GImGui;
5250
35.9k
    IM_ASSERT(g.Initialized);
5251
5252
35.9k
    if (g.FrameCountEnded != g.FrameCount)
5253
35.9k
        EndFrame();
5254
35.9k
    const bool first_render_of_frame = (g.FrameCountRendered != g.FrameCount);
5255
35.9k
    g.FrameCountRendered = g.FrameCount;
5256
35.9k
    g.IO.MetricsRenderWindows = 0;
5257
5258
35.9k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5259
5260
    // Add background ImDrawList (for each active viewport)
5261
71.8k
    for (int n = 0; n != g.Viewports.Size; n++)
5262
35.9k
    {
5263
35.9k
        ImGuiViewportP* viewport = g.Viewports[n];
5264
35.9k
        viewport->DrawDataBuilder.Clear();
5265
35.9k
        if (viewport->DrawLists[0] != NULL)
5266
0
            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5267
35.9k
    }
5268
5269
    // Add ImDrawList to render
5270
35.9k
    ImGuiWindow* windows_to_render_top_most[2];
5271
35.9k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5272
35.9k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5273
143k
    for (int n = 0; n != g.Windows.Size; n++)
5274
107k
    {
5275
107k
        ImGuiWindow* window = g.Windows[n];
5276
107k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5277
107k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5278
35.9k
            AddRootWindowToDrawData(window);
5279
107k
    }
5280
107k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5281
71.8k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5282
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5283
5284
    // Draw modal/window whitening backgrounds
5285
35.9k
    if (first_render_of_frame)
5286
35.9k
        RenderDimmedBackgrounds();
5287
5288
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5289
35.9k
    if (g.IO.MouseDrawCursor && first_render_of_frame && g.MouseCursor != ImGuiMouseCursor_None)
5290
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5291
5292
    // Setup ImDrawData structures for end-user
5293
35.9k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5294
71.8k
    for (int n = 0; n < g.Viewports.Size; n++)
5295
35.9k
    {
5296
35.9k
        ImGuiViewportP* viewport = g.Viewports[n];
5297
35.9k
        viewport->DrawDataBuilder.FlattenIntoSingleLayer();
5298
5299
        // Add foreground ImDrawList (for each active viewport)
5300
35.9k
        if (viewport->DrawLists[1] != NULL)
5301
0
            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5302
5303
35.9k
        SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
5304
35.9k
        ImDrawData* draw_data = viewport->DrawData;
5305
35.9k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5306
35.9k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5307
35.9k
    }
5308
5309
35.9k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5310
35.9k
}
5311
5312
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5313
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5314
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5315
71.8k
{
5316
71.8k
    ImGuiContext& g = *GImGui;
5317
5318
71.8k
    const char* text_display_end;
5319
71.8k
    if (hide_text_after_double_hash)
5320
71.8k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5321
0
    else
5322
0
        text_display_end = text_end;
5323
5324
71.8k
    ImFont* font = g.Font;
5325
71.8k
    const float font_size = g.FontSize;
5326
71.8k
    if (text == text_display_end)
5327
0
        return ImVec2(0.0f, font_size);
5328
71.8k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5329
5330
    // Round
5331
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5332
    // FIXME: Investigate using ceilf or e.g.
5333
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5334
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5335
71.8k
    text_size.x = IM_FLOOR(text_size.x + 0.99999f);
5336
5337
71.8k
    return text_size;
5338
71.8k
}
5339
5340
// Find window given position, search front-to-back
5341
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5342
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5343
// called, aka before the next Begin(). Moving window isn't affected.
5344
static void FindHoveredWindow()
5345
35.9k
{
5346
35.9k
    ImGuiContext& g = *GImGui;
5347
5348
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5349
35.9k
    ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
5350
35.9k
    if (g.MovingWindow)
5351
18
        g.MovingWindow->Viewport = g.MouseViewport;
5352
5353
35.9k
    ImGuiWindow* hovered_window = NULL;
5354
35.9k
    ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
5355
35.9k
    if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5356
18
        hovered_window = g.MovingWindow;
5357
5358
35.9k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5359
35.9k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5360
141k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5361
106k
    {
5362
106k
        ImGuiWindow* window = g.Windows[i];
5363
106k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5364
106k
        if (!window->Active || window->Hidden)
5365
44.9k
            continue;
5366
61.9k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5367
0
            continue;
5368
61.9k
        IM_ASSERT(window->Viewport);
5369
61.9k
        if (window->Viewport != g.MouseViewport)
5370
0
            continue;
5371
5372
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5373
61.9k
        ImRect bb(window->OuterRectClipped);
5374
61.9k
        if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
5375
26.0k
            bb.Expand(padding_regular);
5376
35.9k
        else
5377
35.9k
            bb.Expand(padding_for_resize);
5378
61.9k
        if (!bb.Contains(g.IO.MousePos))
5379
61.1k
            continue;
5380
5381
        // Support for one rectangular hole in any given window
5382
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5383
851
        if (window->HitTestHoleSize.x != 0)
5384
0
        {
5385
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5386
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5387
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
5388
0
                continue;
5389
0
        }
5390
5391
851
        if (hovered_window == NULL)
5392
843
            hovered_window = window;
5393
851
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5394
851
        if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5395
843
            hovered_window_ignoring_moving_window = window;
5396
851
        if (hovered_window && hovered_window_ignoring_moving_window)
5397
843
            break;
5398
851
    }
5399
5400
35.9k
    g.HoveredWindow = hovered_window;
5401
35.9k
    g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
5402
5403
35.9k
    if (g.MovingWindow)
5404
18
        g.MovingWindow->Viewport = moving_window_viewport;
5405
35.9k
}
5406
5407
bool ImGui::IsItemActive()
5408
71.8k
{
5409
71.8k
    ImGuiContext& g = *GImGui;
5410
71.8k
    if (g.ActiveId)
5411
49
        return g.ActiveId == g.LastItemData.ID;
5412
71.7k
    return false;
5413
71.8k
}
5414
5415
bool ImGui::IsItemActivated()
5416
0
{
5417
0
    ImGuiContext& g = *GImGui;
5418
0
    if (g.ActiveId)
5419
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5420
0
            return true;
5421
0
    return false;
5422
0
}
5423
5424
bool ImGui::IsItemDeactivated()
5425
0
{
5426
0
    ImGuiContext& g = *GImGui;
5427
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5428
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5429
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5430
0
}
5431
5432
bool ImGui::IsItemDeactivatedAfterEdit()
5433
0
{
5434
0
    ImGuiContext& g = *GImGui;
5435
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5436
0
}
5437
5438
// == GetItemID() == GetFocusID()
5439
bool ImGui::IsItemFocused()
5440
0
{
5441
0
    ImGuiContext& g = *GImGui;
5442
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5443
0
        return false;
5444
5445
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5446
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5447
0
    ImGuiWindow* window = g.CurrentWindow;
5448
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5449
0
        return false;
5450
5451
0
    return true;
5452
0
}
5453
5454
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5455
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5456
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5457
0
{
5458
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5459
0
}
5460
5461
bool ImGui::IsItemToggledOpen()
5462
0
{
5463
0
    ImGuiContext& g = *GImGui;
5464
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5465
0
}
5466
5467
bool ImGui::IsItemToggledSelection()
5468
0
{
5469
0
    ImGuiContext& g = *GImGui;
5470
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5471
0
}
5472
5473
bool ImGui::IsAnyItemHovered()
5474
0
{
5475
0
    ImGuiContext& g = *GImGui;
5476
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5477
0
}
5478
5479
bool ImGui::IsAnyItemActive()
5480
0
{
5481
0
    ImGuiContext& g = *GImGui;
5482
0
    return g.ActiveId != 0;
5483
0
}
5484
5485
bool ImGui::IsAnyItemFocused()
5486
0
{
5487
0
    ImGuiContext& g = *GImGui;
5488
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5489
0
}
5490
5491
bool ImGui::IsItemVisible()
5492
0
{
5493
0
    ImGuiContext& g = *GImGui;
5494
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5495
0
}
5496
5497
bool ImGui::IsItemEdited()
5498
0
{
5499
0
    ImGuiContext& g = *GImGui;
5500
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5501
0
}
5502
5503
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5504
// FIXME: Although this is exposed, its interaction and ideal idiom with using ImGuiButtonFlags_AllowItemOverlap flag are extremely confusing, need rework.
5505
void ImGui::SetItemAllowOverlap()
5506
0
{
5507
0
    ImGuiContext& g = *GImGui;
5508
0
    ImGuiID id = g.LastItemData.ID;
5509
0
    if (g.HoveredId == id)
5510
0
        g.HoveredIdAllowOverlap = true;
5511
0
    if (g.ActiveId == id)
5512
0
        g.ActiveIdAllowOverlap = true;
5513
0
}
5514
5515
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5516
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5517
21
{
5518
21
    ImGuiContext& g = *GImGui;
5519
21
    IM_ASSERT(g.ActiveId != 0);
5520
21
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5521
21
    g.ActiveIdUsingAllKeyboardKeys = true;
5522
21
    NavMoveRequestCancel();
5523
21
}
5524
5525
ImGuiID ImGui::GetItemID()
5526
0
{
5527
0
    ImGuiContext& g = *GImGui;
5528
0
    return g.LastItemData.ID;
5529
0
}
5530
5531
ImVec2 ImGui::GetItemRectMin()
5532
0
{
5533
0
    ImGuiContext& g = *GImGui;
5534
0
    return g.LastItemData.Rect.Min;
5535
0
}
5536
5537
ImVec2 ImGui::GetItemRectMax()
5538
0
{
5539
0
    ImGuiContext& g = *GImGui;
5540
0
    return g.LastItemData.Rect.Max;
5541
0
}
5542
5543
ImVec2 ImGui::GetItemRectSize()
5544
0
{
5545
0
    ImGuiContext& g = *GImGui;
5546
0
    return g.LastItemData.Rect.GetSize();
5547
0
}
5548
5549
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
5550
35.9k
{
5551
35.9k
    ImGuiContext& g = *GImGui;
5552
35.9k
    ImGuiWindow* parent_window = g.CurrentWindow;
5553
5554
35.9k
    flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoDocking;
5555
35.9k
    flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove);  // Inherit the NoMove flag
5556
5557
    // Size
5558
35.9k
    const ImVec2 content_avail = GetContentRegionAvail();
5559
35.9k
    ImVec2 size = ImFloor(size_arg);
5560
35.9k
    const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
5561
35.9k
    if (size.x <= 0.0f)
5562
33.0k
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too many issues)
5563
35.9k
    if (size.y <= 0.0f)
5564
31.3k
        size.y = ImMax(content_avail.y + size.y, 4.0f);
5565
35.9k
    SetNextWindowSize(size);
5566
5567
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5568
35.9k
    const char* temp_window_name;
5569
35.9k
    if (name)
5570
35.9k
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5571
0
    else
5572
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5573
5574
35.9k
    const float backup_border_size = g.Style.ChildBorderSize;
5575
35.9k
    if (!border)
5576
22.7k
        g.Style.ChildBorderSize = 0.0f;
5577
35.9k
    bool ret = Begin(temp_window_name, NULL, flags);
5578
35.9k
    g.Style.ChildBorderSize = backup_border_size;
5579
5580
35.9k
    ImGuiWindow* child_window = g.CurrentWindow;
5581
35.9k
    child_window->ChildId = id;
5582
35.9k
    child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
5583
5584
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5585
    // While this is not really documented/defined, it seems that the expected thing to do.
5586
35.9k
    if (child_window->BeginCount == 1)
5587
35.9k
        parent_window->DC.CursorPos = child_window->Pos;
5588
5589
    // Process navigation-in immediately so NavInit can run on first frame
5590
    // Can enter a child if (A) it has navigatable items or (B) it can be scrolled.
5591
35.9k
    const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
5592
35.9k
    if (g.ActiveId == temp_id_for_activation)
5593
1
        ClearActiveID();
5594
35.9k
    if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5595
4
    {
5596
4
        FocusWindow(child_window);
5597
4
        NavInitWindow(child_window, false);
5598
4
        SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5599
4
        g.ActiveIdSource = g.NavInputSource;
5600
4
    }
5601
35.9k
    return ret;
5602
35.9k
}
5603
5604
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5605
35.9k
{
5606
35.9k
    ImGuiWindow* window = GetCurrentWindow();
5607
35.9k
    return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
5608
35.9k
}
5609
5610
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5611
0
{
5612
0
    IM_ASSERT(id != 0);
5613
0
    return BeginChildEx(NULL, id, size_arg, border, extra_flags);
5614
0
}
5615
5616
void ImGui::EndChild()
5617
35.9k
{
5618
35.9k
    ImGuiContext& g = *GImGui;
5619
35.9k
    ImGuiWindow* window = g.CurrentWindow;
5620
5621
35.9k
    IM_ASSERT(g.WithinEndChild == false);
5622
35.9k
    IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5623
5624
35.9k
    g.WithinEndChild = true;
5625
35.9k
    if (window->BeginCount > 1)
5626
0
    {
5627
0
        End();
5628
0
    }
5629
35.9k
    else
5630
35.9k
    {
5631
35.9k
        ImVec2 sz = window->Size;
5632
35.9k
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
5633
33.0k
            sz.x = ImMax(4.0f, sz.x);
5634
35.9k
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
5635
31.3k
            sz.y = ImMax(4.0f, sz.y);
5636
35.9k
        End();
5637
5638
35.9k
        ImGuiWindow* parent_window = g.CurrentWindow;
5639
35.9k
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
5640
35.9k
        ItemSize(sz);
5641
35.9k
        if ((window->DC.NavLayersActiveMask != 0 || window->DC.NavWindowHasScrollY) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
5642
32.5k
        {
5643
32.5k
            ItemAdd(bb, window->ChildId);
5644
32.5k
            RenderNavHighlight(bb, window->ChildId);
5645
5646
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5647
32.5k
            if (window->DC.NavLayersActiveMask == 0 && window == g.NavWindow)
5648
27.4k
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
5649
32.5k
        }
5650
3.33k
        else
5651
3.33k
        {
5652
            // Not navigable into
5653
3.33k
            ItemAdd(bb, 0);
5654
5655
            // But when flattened we directly reach items, adjust active layer mask accordingly
5656
3.33k
            if (window->Flags & ImGuiWindowFlags_NavFlattened)
5657
0
                parent_window->DC.NavLayersActiveMaskNext |= window->DC.NavLayersActiveMaskNext;
5658
3.33k
        }
5659
35.9k
        if (g.HoveredWindow == window)
5660
2
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5661
35.9k
    }
5662
35.9k
    g.WithinEndChild = false;
5663
35.9k
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5664
35.9k
}
5665
5666
// Helper to create a child window / scrolling region that looks like a normal widget frame.
5667
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
5668
0
{
5669
0
    ImGuiContext& g = *GImGui;
5670
0
    const ImGuiStyle& style = g.Style;
5671
0
    PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
5672
0
    PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
5673
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
5674
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
5675
0
    bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
5676
0
    PopStyleVar(3);
5677
0
    PopStyleColor();
5678
0
    return ret;
5679
0
}
5680
5681
void ImGui::EndChildFrame()
5682
0
{
5683
0
    EndChild();
5684
0
}
5685
5686
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5687
6
{
5688
6
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5689
6
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5690
6
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5691
6
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
5692
6
}
5693
5694
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5695
107k
{
5696
107k
    ImGuiContext& g = *GImGui;
5697
107k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5698
107k
}
5699
5700
ImGuiWindow* ImGui::FindWindowByName(const char* name)
5701
107k
{
5702
107k
    ImGuiID id = ImHashStr(name);
5703
107k
    return FindWindowByID(id);
5704
107k
}
5705
5706
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5707
0
{
5708
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5709
0
    window->ViewportPos = main_viewport->Pos;
5710
0
    if (settings->ViewportId)
5711
0
    {
5712
0
        window->ViewportId = settings->ViewportId;
5713
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5714
0
    }
5715
0
    window->Pos = ImFloor(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5716
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
5717
0
        window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y));
5718
0
    window->Collapsed = settings->Collapsed;
5719
0
    window->DockId = settings->DockId;
5720
0
    window->DockOrder = settings->DockOrder;
5721
0
}
5722
5723
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5724
107k
{
5725
107k
    ImGuiContext& g = *GImGui;
5726
5727
107k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5728
107k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5729
107k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
5730
2
    {
5731
2
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5732
2
        g.WindowsFocusOrder.push_back(window);
5733
2
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5734
2
    }
5735
107k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
5736
0
    {
5737
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5738
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5739
0
            g.WindowsFocusOrder[n]->FocusOrder--;
5740
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
5741
0
        window->FocusOrder = -1;
5742
0
    }
5743
107k
    window->IsExplicitChild = new_is_explicit_child;
5744
107k
}
5745
5746
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5747
3
{
5748
    // Initial window state with e.g. default/arbitrary window position
5749
    // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5750
3
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5751
3
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
5752
3
    window->ViewportPos = main_viewport->Pos;
5753
3
    window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
5754
5755
3
    if (settings != NULL)
5756
0
    {
5757
0
        SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
5758
0
        ApplyWindowSettings(window, settings);
5759
0
    }
5760
3
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5761
5762
3
    if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5763
0
    {
5764
0
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
5765
0
        window->AutoFitOnlyGrows = false;
5766
0
    }
5767
3
    else
5768
3
    {
5769
3
        if (window->Size.x <= 0.0f)
5770
3
            window->AutoFitFramesX = 2;
5771
3
        if (window->Size.y <= 0.0f)
5772
3
            window->AutoFitFramesY = 2;
5773
3
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5774
3
    }
5775
3
}
5776
5777
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5778
3
{
5779
    // Create window the first time
5780
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5781
3
    ImGuiContext& g = *GImGui;
5782
3
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5783
3
    window->Flags = flags;
5784
3
    g.WindowsById.SetVoidPtr(window->ID, window);
5785
5786
3
    ImGuiWindowSettings* settings = NULL;
5787
3
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5788
2
        if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
5789
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
5790
5791
3
    InitOrLoadWindowSettings(window, settings);
5792
5793
3
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5794
0
        g.Windows.push_front(window); // Quite slow but rare and only once
5795
3
    else
5796
3
        g.Windows.push_back(window);
5797
5798
3
    return window;
5799
3
}
5800
5801
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
5802
0
{
5803
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
5804
0
}
5805
5806
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
5807
143k
{
5808
143k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
5809
143k
}
5810
5811
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
5812
215k
{
5813
215k
    ImGuiContext& g = *GImGui;
5814
215k
    ImVec2 new_size = size_desired;
5815
215k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
5816
0
    {
5817
        // Using -1,-1 on either X/Y axis to preserve the current size.
5818
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
5819
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
5820
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
5821
0
        if (g.NextWindowData.SizeCallback)
5822
0
        {
5823
0
            ImGuiSizeCallbackData data;
5824
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
5825
0
            data.Pos = window->Pos;
5826
0
            data.CurrentSize = window->SizeFull;
5827
0
            data.DesiredSize = new_size;
5828
0
            g.NextWindowData.SizeCallback(&data);
5829
0
            new_size = data.DesiredSize;
5830
0
        }
5831
0
        new_size.x = IM_FLOOR(new_size.x);
5832
0
        new_size.y = IM_FLOOR(new_size.y);
5833
0
    }
5834
5835
    // Minimum size
5836
215k
    if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
5837
143k
    {
5838
143k
        ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
5839
143k
        new_size = ImMax(new_size, g.Style.WindowMinSize);
5840
143k
        const float minimum_height = window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f);
5841
143k
        new_size.y = ImMax(new_size.y, minimum_height); // Reduce artifacts with very small windows
5842
143k
    }
5843
215k
    return new_size;
5844
215k
}
5845
5846
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
5847
107k
{
5848
107k
    bool preserve_old_content_sizes = false;
5849
107k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
5850
0
        preserve_old_content_sizes = true;
5851
107k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
5852
9.83k
        preserve_old_content_sizes = true;
5853
107k
    if (preserve_old_content_sizes)
5854
9.83k
    {
5855
9.83k
        *content_size_current = window->ContentSize;
5856
9.83k
        *content_size_ideal = window->ContentSizeIdeal;
5857
9.83k
        return;
5858
9.83k
    }
5859
5860
97.8k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
5861
97.8k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
5862
97.8k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
5863
97.8k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
5864
97.8k
}
5865
5866
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
5867
107k
{
5868
107k
    ImGuiContext& g = *GImGui;
5869
107k
    ImGuiStyle& style = g.Style;
5870
107k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
5871
107k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
5872
107k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
5873
107k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
5874
107k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
5875
0
    {
5876
        // Tooltip always resize
5877
0
        return size_desired;
5878
0
    }
5879
107k
    else
5880
107k
    {
5881
        // Maximum window size is determined by the viewport size or monitor size
5882
107k
        const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
5883
107k
        const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
5884
107k
        ImVec2 size_min = style.WindowMinSize;
5885
107k
        if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
5886
0
            size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
5887
5888
107k
        ImVec2 avail_size = window->Viewport->WorkSize;
5889
107k
        if (window->ViewportOwned)
5890
0
            avail_size = ImVec2(FLT_MAX, FLT_MAX);
5891
107k
        const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
5892
107k
        if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
5893
0
            avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize;
5894
107k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));
5895
5896
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
5897
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
5898
107k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5899
107k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x  && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
5900
107k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
5901
107k
        if (will_have_scrollbar_x)
5902
35.9k
            size_auto_fit.y += style.ScrollbarSize;
5903
107k
        if (will_have_scrollbar_y)
5904
210
            size_auto_fit.x += style.ScrollbarSize;
5905
107k
        return size_auto_fit;
5906
107k
    }
5907
107k
}
5908
5909
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
5910
0
{
5911
0
    ImVec2 size_contents_current;
5912
0
    ImVec2 size_contents_ideal;
5913
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
5914
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
5915
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5916
0
    return size_final;
5917
0
}
5918
5919
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
5920
107k
{
5921
107k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
5922
0
        return ImGuiCol_PopupBg;
5923
107k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
5924
35.9k
        return ImGuiCol_ChildBg;
5925
71.8k
    return ImGuiCol_WindowBg;
5926
107k
}
5927
5928
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
5929
0
{
5930
0
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
5931
0
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
5932
0
    ImVec2 size_expected = pos_max - pos_min;
5933
0
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
5934
0
    *out_pos = pos_min;
5935
0
    if (corner_norm.x == 0.0f)
5936
0
        out_pos->x -= (size_constrained.x - size_expected.x);
5937
0
    if (corner_norm.y == 0.0f)
5938
0
        out_pos->y -= (size_constrained.y - size_expected.y);
5939
0
    *out_size = size_constrained;
5940
0
}
5941
5942
// Data for resizing from corner
5943
struct ImGuiResizeGripDef
5944
{
5945
    ImVec2  CornerPosN;
5946
    ImVec2  InnerDir;
5947
    int     AngleMin12, AngleMax12;
5948
};
5949
static const ImGuiResizeGripDef resize_grip_def[4] =
5950
{
5951
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
5952
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
5953
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
5954
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
5955
};
5956
5957
// Data for resizing from borders
5958
struct ImGuiResizeBorderDef
5959
{
5960
    ImVec2 InnerDir;
5961
    ImVec2 SegmentN1, SegmentN2;
5962
    float  OuterAngle;
5963
};
5964
static const ImGuiResizeBorderDef resize_border_def[4] =
5965
{
5966
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
5967
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
5968
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
5969
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
5970
};
5971
5972
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
5973
0
{
5974
0
    ImRect rect = window->Rect();
5975
0
    if (thickness == 0.0f)
5976
0
        rect.Max -= ImVec2(1, 1);
5977
0
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
5978
0
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
5979
0
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
5980
0
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
5981
0
    IM_ASSERT(0);
5982
0
    return ImRect();
5983
0
}
5984
5985
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
5986
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
5987
0
{
5988
0
    IM_ASSERT(n >= 0 && n < 4);
5989
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
5990
0
    id = ImHashStr("#RESIZE", 0, id);
5991
0
    id = ImHashData(&n, sizeof(int), id);
5992
0
    return id;
5993
0
}
5994
5995
// Borders (Left, Right, Up, Down)
5996
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
5997
0
{
5998
0
    IM_ASSERT(dir >= 0 && dir < 4);
5999
0
    int n = (int)dir + 4;
6000
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6001
0
    id = ImHashStr("#RESIZE", 0, id);
6002
0
    id = ImHashData(&n, sizeof(int), id);
6003
0
    return id;
6004
0
}
6005
6006
// Handle resize for: Resize Grips, Borders, Gamepad
6007
// Return true when using auto-fit (double-click on resize grip)
6008
static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
6009
107k
{
6010
107k
    ImGuiContext& g = *GImGui;
6011
107k
    ImGuiWindowFlags flags = window->Flags;
6012
6013
107k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6014
35.9k
        return false;
6015
71.8k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6016
35.9k
        return false;
6017
6018
35.9k
    bool ret_auto_fit = false;
6019
35.9k
    const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
6020
35.9k
    const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6021
35.9k
    const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
6022
35.9k
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6023
6024
35.9k
    ImRect clamp_rect = visibility_rect;
6025
35.9k
    const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6026
35.9k
    if (window_move_from_title_bar)
6027
0
        clamp_rect.Min.y -= window->TitleBarHeight();
6028
6029
35.9k
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
6030
35.9k
    ImVec2 size_target(FLT_MAX, FLT_MAX);
6031
6032
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6033
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6034
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6035
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
6036
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6037
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6038
35.9k
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6039
35.9k
    if (clip_with_viewport_rect)
6040
35.9k
        window->ClipRect = window->Viewport->GetMainRect();
6041
6042
    // Resize grips and borders are on layer 1
6043
35.9k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6044
6045
    // Manual resize grips
6046
35.9k
    PushID("#RESIZE");
6047
71.8k
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6048
35.9k
    {
6049
35.9k
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6050
35.9k
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6051
6052
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6053
35.9k
        bool hovered, held;
6054
35.9k
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6055
35.9k
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6056
35.9k
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6057
35.9k
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6058
35.9k
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6059
35.9k
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6060
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6061
35.9k
        if (hovered || held)
6062
0
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6063
6064
35.9k
        if (held && g.IO.MouseClickedCount[0] == 2 && resize_grip_n == 0)
6065
0
        {
6066
            // Manual auto-fit when double-clicking
6067
0
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6068
0
            ret_auto_fit = true;
6069
0
            ClearActiveID();
6070
0
        }
6071
35.9k
        else if (held)
6072
0
        {
6073
            // Resize from any of the four corners
6074
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6075
0
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? clamp_rect.Min.x : -FLT_MAX, (def.CornerPosN.y == 1.0f || (def.CornerPosN.y == 0.0f && window_move_from_title_bar)) ? clamp_rect.Min.y : -FLT_MAX);
6076
0
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX);
6077
0
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6078
0
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6079
0
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6080
0
        }
6081
6082
        // Only lower-left grip is visible before hovering/activating
6083
35.9k
        if (resize_grip_n == 0 || held || hovered)
6084
35.9k
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6085
35.9k
    }
6086
35.9k
    for (int border_n = 0; border_n < resize_border_count; border_n++)
6087
0
    {
6088
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6089
0
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6090
6091
0
        bool hovered, held;
6092
0
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6093
0
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6094
0
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6095
0
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6096
        //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6097
0
        if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
6098
0
        {
6099
0
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6100
0
            if (held)
6101
0
                *border_held = border_n;
6102
0
        }
6103
0
        if (held)
6104
0
        {
6105
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX);
6106
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6107
0
            ImVec2 border_target = window->Pos;
6108
0
            border_target[axis] = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING;
6109
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
6110
0
            CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6111
0
        }
6112
0
    }
6113
35.9k
    PopID();
6114
6115
    // Restore nav layer
6116
35.9k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6117
6118
    // Navigation resize (keyboard/gamepad)
6119
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6120
    // Not even sure the callback works here.
6121
35.9k
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6122
0
    {
6123
0
        ImVec2 nav_resize_dir;
6124
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6125
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6126
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6127
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6128
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6129
0
        {
6130
0
            const float NAV_RESIZE_SPEED = 600.0f;
6131
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6132
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6133
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
6134
0
            g.NavWindowingToggleLayer = false;
6135
0
            g.NavDisableMouseHover = true;
6136
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6137
0
            ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaSize);
6138
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6139
0
            {
6140
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6141
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6142
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6143
0
            }
6144
0
        }
6145
0
    }
6146
6147
    // Apply back modified position/size to window
6148
35.9k
    if (size_target.x != FLT_MAX)
6149
0
    {
6150
0
        window->SizeFull = size_target;
6151
0
        MarkIniSettingsDirty(window);
6152
0
    }
6153
35.9k
    if (pos_target.x != FLT_MAX)
6154
0
    {
6155
0
        window->Pos = ImFloor(pos_target);
6156
0
        MarkIniSettingsDirty(window);
6157
0
    }
6158
6159
35.9k
    window->Size = window->SizeFull;
6160
35.9k
    return ret_auto_fit;
6161
71.8k
}
6162
6163
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6164
71.8k
{
6165
71.8k
    ImGuiContext& g = *GImGui;
6166
71.8k
    ImVec2 size_for_clamping = window->Size;
6167
71.8k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost))
6168
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6169
71.8k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6170
71.8k
}
6171
6172
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6173
107k
{
6174
107k
    ImGuiContext& g = *GImGui;
6175
107k
    float rounding = window->WindowRounding;
6176
107k
    float border_size = window->WindowBorderSize;
6177
107k
    if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
6178
84.9k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
6179
6180
107k
    int border_held = window->ResizeBorderHeld;
6181
107k
    if (border_held != -1)
6182
0
    {
6183
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_held];
6184
0
        ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
6185
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6186
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6187
0
        window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), 0, ImMax(2.0f, border_size)); // Thicker than usual
6188
0
    }
6189
107k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6190
0
    {
6191
0
        float y = window->Pos.y + window->TitleBarHeight() - 1;
6192
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
6193
0
    }
6194
107k
}
6195
6196
// Draw background and borders
6197
// Draw and handle scrollbars
6198
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6199
107k
{
6200
107k
    ImGuiContext& g = *GImGui;
6201
107k
    ImGuiStyle& style = g.Style;
6202
107k
    ImGuiWindowFlags flags = window->Flags;
6203
6204
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6205
107k
    IM_ASSERT(window->BeginCount == 0);
6206
107k
    window->SkipItems = false;
6207
6208
    // Draw window + handle manual resize
6209
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6210
107k
    const float window_rounding = window->WindowRounding;
6211
107k
    const float window_border_size = window->WindowBorderSize;
6212
107k
    if (window->Collapsed)
6213
0
    {
6214
        // Title bar only
6215
0
        const float backup_border_size = style.FrameBorderSize;
6216
0
        g.Style.FrameBorderSize = window->WindowBorderSize;
6217
0
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6218
0
        if (window->ViewportOwned)
6219
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6220
0
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6221
0
        g.Style.FrameBorderSize = backup_border_size;
6222
0
    }
6223
107k
    else
6224
107k
    {
6225
        // Window background
6226
107k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6227
107k
        {
6228
107k
            bool is_docking_transparent_payload = false;
6229
107k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6230
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6231
0
                    is_docking_transparent_payload = true;
6232
6233
107k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6234
107k
            if (window->ViewportOwned)
6235
0
            {
6236
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6237
0
                if (is_docking_transparent_payload)
6238
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6239
0
            }
6240
107k
            else
6241
107k
            {
6242
                // Adjust alpha. For docking
6243
107k
                bool override_alpha = false;
6244
107k
                float alpha = 1.0f;
6245
107k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6246
0
                {
6247
0
                    alpha = g.NextWindowData.BgAlphaVal;
6248
0
                    override_alpha = true;
6249
0
                }
6250
107k
                if (is_docking_transparent_payload)
6251
0
                {
6252
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6253
0
                    override_alpha = true;
6254
0
                }
6255
107k
                if (override_alpha)
6256
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6257
107k
            }
6258
6259
            // Render, for docked windows and host windows we ensure bg goes before decorations
6260
107k
            if (window->DockIsActive)
6261
0
                window->DockNode->LastBgColor = bg_col;
6262
107k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6263
107k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6264
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6265
107k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6266
107k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6267
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6268
107k
        }
6269
107k
        if (window->DockIsActive)
6270
0
            window->DockNode->IsBgDrawnThisFrame = true;
6271
6272
        // Title bar
6273
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6274
        // in order for their pos/size to be matching their undocking state.)
6275
107k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6276
71.8k
        {
6277
71.8k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6278
71.8k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6279
71.8k
        }
6280
6281
        // Menu bar
6282
107k
        if (flags & ImGuiWindowFlags_MenuBar)
6283
0
        {
6284
0
            ImRect menu_bar_rect = window->MenuBarRect();
6285
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6286
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6287
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6288
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6289
0
        }
6290
6291
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6292
107k
        ImGuiDockNode* node = window->DockNode;
6293
107k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6294
0
        {
6295
0
            float unhide_sz_draw = ImFloor(g.FontSize * 0.70f);
6296
0
            float unhide_sz_hit = ImFloor(g.FontSize * 0.55f);
6297
0
            ImVec2 p = node->Pos;
6298
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6299
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6300
0
            KeepAliveID(unhide_id);
6301
0
            bool hovered, held;
6302
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6303
0
                node->WantHiddenTabBarToggle = true;
6304
0
            else if (held && IsMouseDragging(0))
6305
0
                StartMouseMovingWindowOrNode(window, node, true);
6306
6307
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6308
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6309
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6310
0
        }
6311
6312
        // Scrollbars
6313
107k
        if (window->ScrollbarX)
6314
35.9k
            Scrollbar(ImGuiAxis_X);
6315
107k
        if (window->ScrollbarY)
6316
36.4k
            Scrollbar(ImGuiAxis_Y);
6317
6318
        // Render resize grips (after their input handling so we don't have a frame of latency)
6319
107k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6320
71.8k
        {
6321
143k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6322
71.8k
            {
6323
71.8k
                const ImU32 col = resize_grip_col[resize_grip_n];
6324
71.8k
                if ((col & IM_COL32_A_MASK) == 0)
6325
35.9k
                    continue;
6326
35.9k
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6327
35.9k
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6328
35.9k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6329
35.9k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6330
35.9k
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6331
35.9k
                window->DrawList->PathFillConvex(col);
6332
35.9k
            }
6333
71.8k
        }
6334
6335
        // Borders (for dock node host they will be rendered over after the tab bar)
6336
107k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6337
107k
            RenderWindowOuterBorders(window);
6338
107k
    }
6339
107k
}
6340
6341
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6342
// Render title text, collapse button, close button
6343
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6344
71.8k
{
6345
71.8k
    ImGuiContext& g = *GImGui;
6346
71.8k
    ImGuiStyle& style = g.Style;
6347
71.8k
    ImGuiWindowFlags flags = window->Flags;
6348
6349
71.8k
    const bool has_close_button = (p_open != NULL);
6350
71.8k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6351
6352
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6353
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6354
71.8k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6355
71.8k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6356
71.8k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6357
6358
    // Layout buttons
6359
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6360
71.8k
    float pad_l = style.FramePadding.x;
6361
71.8k
    float pad_r = style.FramePadding.x;
6362
71.8k
    float button_sz = g.FontSize;
6363
71.8k
    ImVec2 close_button_pos;
6364
71.8k
    ImVec2 collapse_button_pos;
6365
71.8k
    if (has_close_button)
6366
0
    {
6367
0
        pad_r += button_sz;
6368
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
6369
0
    }
6370
71.8k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6371
0
    {
6372
0
        pad_r += button_sz;
6373
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
6374
0
    }
6375
71.8k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6376
71.8k
    {
6377
71.8k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
6378
71.8k
        pad_l += button_sz;
6379
71.8k
    }
6380
6381
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6382
71.8k
    if (has_collapse_button)
6383
71.8k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6384
0
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6385
6386
    // Close button
6387
71.8k
    if (has_close_button)
6388
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6389
0
            *p_open = false;
6390
6391
71.8k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6392
71.8k
    g.CurrentItemFlags = item_flags_backup;
6393
6394
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6395
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6396
71.8k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6397
71.8k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6398
6399
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6400
    // while uncentered title text will still reach edges correctly.
6401
71.8k
    if (pad_l > style.FramePadding.x)
6402
71.8k
        pad_l += g.Style.ItemInnerSpacing.x;
6403
71.8k
    if (pad_r > style.FramePadding.x)
6404
0
        pad_r += g.Style.ItemInnerSpacing.x;
6405
71.8k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6406
0
    {
6407
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6408
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6409
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6410
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6411
0
    }
6412
6413
71.8k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6414
71.8k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6415
71.8k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6416
0
    {
6417
0
        ImVec2 marker_pos;
6418
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6419
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6420
0
        if (marker_pos.x > layout_r.Min.x)
6421
0
        {
6422
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6423
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6424
0
        }
6425
0
    }
6426
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6427
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6428
71.8k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6429
71.8k
}
6430
6431
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6432
107k
{
6433
107k
    window->ParentWindow = parent_window;
6434
107k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6435
107k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6436
35.9k
    {
6437
35.9k
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6438
35.9k
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6439
35.9k
            window->RootWindow = parent_window->RootWindow;
6440
35.9k
    }
6441
107k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6442
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6443
107k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6444
35.9k
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6445
107k
    while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
6446
0
    {
6447
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6448
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6449
0
    }
6450
107k
}
6451
6452
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6453
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6454
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6455
// - Window             // FindBlockingModal() returns Modal1
6456
//   - Window           //                  .. returns Modal1
6457
//   - Modal1           //                  .. returns Modal2
6458
//      - Window        //                  .. returns Modal2
6459
//          - Window    //                  .. returns Modal2
6460
//          - Modal2    //                  .. returns Modal2
6461
// Notes:
6462
// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6463
//   Only difference is here we check for ->Active/WasActive but it may be unecessary.
6464
ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6465
522
{
6466
522
    ImGuiContext& g = *GImGui;
6467
522
    if (g.OpenPopupStack.Size <= 0)
6468
522
        return NULL;
6469
6470
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6471
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
6472
0
    {
6473
0
        ImGuiWindow* popup_window = g.OpenPopupStack.Data[i].Window;
6474
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6475
0
            continue;
6476
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6477
0
            continue;
6478
0
        if (window == NULL)                                         // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6479
0
            return popup_window;
6480
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window is rendered over last modal, no render order change needed.
6481
0
            break;
6482
0
        for (ImGuiWindow* parent = popup_window->ParentWindowInBeginStack->RootWindow; parent != NULL; parent = parent->ParentWindowInBeginStack->RootWindow)
6483
0
            if (IsWindowWithinBeginStackOf(window, parent))
6484
0
                return popup_window;                                // Place window above its begin stack parent.
6485
0
    }
6486
0
    return NULL;
6487
0
}
6488
6489
// Push a new Dear ImGui window to add widgets to.
6490
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6491
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6492
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6493
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6494
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6495
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6496
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6497
107k
{
6498
107k
    ImGuiContext& g = *GImGui;
6499
107k
    const ImGuiStyle& style = g.Style;
6500
107k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6501
107k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6502
107k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6503
6504
    // Find or create
6505
107k
    ImGuiWindow* window = FindWindowByName(name);
6506
107k
    const bool window_just_created = (window == NULL);
6507
107k
    if (window_just_created)
6508
3
        window = CreateNewWindow(name, flags);
6509
6510
    // Automatically disable manual moving/resizing when NoInputs is set
6511
107k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6512
0
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6513
6514
107k
    if (flags & ImGuiWindowFlags_NavFlattened)
6515
107k
        IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
6516
6517
107k
    const int current_frame = g.FrameCount;
6518
107k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6519
107k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6520
6521
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6522
107k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6523
107k
    if (flags & ImGuiWindowFlags_Popup)
6524
0
    {
6525
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6526
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6527
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6528
0
    }
6529
6530
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6531
107k
    const bool window_was_appearing = window->Appearing;
6532
107k
    if (first_begin_of_the_frame)
6533
107k
    {
6534
107k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6535
107k
        window->Appearing = window_just_activated_by_user;
6536
107k
        if (window->Appearing)
6537
3
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6538
107k
        window->FlagsPreviousFrame = window->Flags;
6539
107k
        window->Flags = (ImGuiWindowFlags)flags;
6540
107k
        window->LastFrameActive = current_frame;
6541
107k
        window->LastTimeActive = (float)g.Time;
6542
107k
        window->BeginOrderWithinParent = 0;
6543
107k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6544
107k
    }
6545
0
    else
6546
0
    {
6547
0
        flags = window->Flags;
6548
0
    }
6549
6550
    // Docking
6551
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6552
107k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6553
107k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6554
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6555
107k
    if (first_begin_of_the_frame)
6556
107k
    {
6557
107k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6558
107k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6559
107k
        bool dock_node_was_visible = window->DockNodeIsVisible;
6560
107k
        bool dock_tab_was_visible = window->DockTabIsVisible;
6561
107k
        if (has_dock_node || new_auto_dock_node)
6562
0
        {
6563
0
            BeginDocked(window, p_open);
6564
0
            flags = window->Flags;
6565
0
            if (window->DockIsActive)
6566
0
            {
6567
0
                IM_ASSERT(window->DockNode != NULL);
6568
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6569
0
            }
6570
6571
            // Amend the Appearing flag
6572
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6573
0
            {
6574
0
                window->Appearing = true;
6575
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6576
0
            }
6577
0
        }
6578
107k
        else
6579
107k
        {
6580
107k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6581
107k
        }
6582
107k
    }
6583
6584
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
6585
107k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6586
107k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6587
107k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6588
6589
    // We allow window memory to be compacted so recreate the base stack when needed.
6590
107k
    if (window->IDStack.Size == 0)
6591
0
        window->IDStack.push_back(window->ID);
6592
6593
    // Add to stack
6594
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6595
107k
    g.CurrentWindow = window;
6596
107k
    ImGuiWindowStackData window_stack_data;
6597
107k
    window_stack_data.Window = window;
6598
107k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6599
107k
    window_stack_data.StackSizesOnBegin.SetToContextState(&g);
6600
107k
    g.CurrentWindowStack.push_back(window_stack_data);
6601
107k
    if (flags & ImGuiWindowFlags_ChildMenu)
6602
0
        g.BeginMenuCount++;
6603
6604
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6605
107k
    if (first_begin_of_the_frame)
6606
107k
    {
6607
107k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
6608
107k
        window->ParentWindowInBeginStack = parent_window_in_stack;
6609
107k
    }
6610
6611
    // Add to focus scope stack
6612
107k
    PushFocusScope(window->ID);
6613
107k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6614
107k
    g.CurrentWindow = NULL;
6615
6616
    // Add to popup stack
6617
107k
    if (flags & ImGuiWindowFlags_Popup)
6618
0
    {
6619
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6620
0
        popup_ref.Window = window;
6621
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6622
0
        g.BeginPopupStack.push_back(popup_ref);
6623
0
        window->PopupId = popup_ref.PopupId;
6624
0
    }
6625
6626
    // Process SetNextWindow***() calls
6627
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
6628
107k
    bool window_pos_set_by_api = false;
6629
107k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6630
107k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6631
0
    {
6632
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6633
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
6634
0
        {
6635
            // May be processed on the next frame if this is our first frame and we are measuring size
6636
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6637
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
6638
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6639
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6640
0
        }
6641
0
        else
6642
0
        {
6643
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
6644
0
        }
6645
0
    }
6646
107k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6647
71.8k
    {
6648
71.8k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6649
71.8k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6650
71.8k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
6651
71.8k
    }
6652
107k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6653
0
    {
6654
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
6655
0
        {
6656
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6657
0
            window->ScrollTargetCenterRatio.x = 0.0f;
6658
0
        }
6659
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
6660
0
        {
6661
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6662
0
            window->ScrollTargetCenterRatio.y = 0.0f;
6663
0
        }
6664
0
    }
6665
107k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6666
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6667
107k
    else if (first_begin_of_the_frame)
6668
107k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6669
107k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
6670
0
        window->WindowClass = g.NextWindowData.WindowClass;
6671
107k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6672
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
6673
107k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6674
0
        FocusWindow(window);
6675
107k
    if (window->Appearing)
6676
3
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
6677
6678
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
6679
107k
    if (first_begin_of_the_frame)
6680
107k
    {
6681
        // Initialize
6682
107k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6683
107k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6684
107k
        window->Active = true;
6685
107k
        window->HasCloseButton = (p_open != NULL);
6686
107k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6687
107k
        window->IDStack.resize(1);
6688
107k
        window->DrawList->_ResetForNewFrame();
6689
107k
        window->DC.CurrentTableIdx = -1;
6690
107k
        if (flags & ImGuiWindowFlags_DockNodeHost)
6691
0
        {
6692
0
            window->DrawList->ChannelsSplit(2);
6693
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
6694
0
        }
6695
6696
        // Restore buffer capacity when woken from a compacted state, to avoid
6697
107k
        if (window->MemoryCompacted)
6698
0
            GcAwakeTransientWindowBuffers(window);
6699
6700
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6701
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
6702
107k
        bool window_title_visible_elsewhere = false;
6703
107k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
6704
0
            window_title_visible_elsewhere = true;
6705
107k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
6706
0
            window_title_visible_elsewhere = true;
6707
107k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
6708
0
        {
6709
0
            size_t buf_len = (size_t)window->NameBufLen;
6710
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
6711
0
            window->NameBufLen = (int)buf_len;
6712
0
        }
6713
6714
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6715
6716
        // Update contents size from last frame for auto-fitting (or use explicit size)
6717
107k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
6718
6719
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
6720
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
6721
        // it has a single usage before this code block and may be set below before it is finally checked.
6722
107k
        if (window->HiddenFramesCanSkipItems > 0)
6723
9.83k
            window->HiddenFramesCanSkipItems--;
6724
107k
        if (window->HiddenFramesCannotSkipItems > 0)
6725
2
            window->HiddenFramesCannotSkipItems--;
6726
107k
        if (window->HiddenFramesForRenderOnly > 0)
6727
0
            window->HiddenFramesForRenderOnly--;
6728
6729
        // Hide new windows for one frame until they calculate their size
6730
107k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
6731
1
            window->HiddenFramesCannotSkipItems = 1;
6732
6733
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
6734
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
6735
107k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
6736
0
        {
6737
0
            window->HiddenFramesCannotSkipItems = 1;
6738
0
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
6739
0
            {
6740
0
                if (!window_size_x_set_by_api)
6741
0
                    window->Size.x = window->SizeFull.x = 0.f;
6742
0
                if (!window_size_y_set_by_api)
6743
0
                    window->Size.y = window->SizeFull.y = 0.f;
6744
0
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
6745
0
            }
6746
0
        }
6747
6748
        // SELECT VIEWPORT
6749
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
6750
6751
107k
        WindowSelectViewport(window);
6752
107k
        SetCurrentViewport(window, window->Viewport);
6753
107k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6754
107k
        SetCurrentWindow(window);
6755
107k
        flags = window->Flags;
6756
6757
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
6758
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
6759
6760
107k
        if (flags & ImGuiWindowFlags_ChildWindow)
6761
35.9k
            window->WindowBorderSize = style.ChildBorderSize;
6762
71.8k
        else
6763
71.8k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
6764
107k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
6765
22.7k
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
6766
84.9k
        else
6767
84.9k
            window->WindowPadding = style.WindowPadding;
6768
6769
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
6770
107k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
6771
107k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
6772
6773
107k
        bool use_current_size_for_scrollbar_x = window_just_created;
6774
107k
        bool use_current_size_for_scrollbar_y = window_just_created;
6775
6776
        // Collapse window by double-clicking on title bar
6777
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
6778
107k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
6779
71.8k
        {
6780
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
6781
71.8k
            ImRect title_bar_rect = window->TitleBarRect();
6782
71.8k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseClickedCount[0] == 2)
6783
0
                window->WantCollapseToggle = true;
6784
71.8k
            if (window->WantCollapseToggle)
6785
0
            {
6786
0
                window->Collapsed = !window->Collapsed;
6787
0
                if (!window->Collapsed)
6788
0
                    use_current_size_for_scrollbar_y = true;
6789
0
                MarkIniSettingsDirty(window);
6790
0
            }
6791
71.8k
        }
6792
35.9k
        else
6793
35.9k
        {
6794
35.9k
            window->Collapsed = false;
6795
35.9k
        }
6796
107k
        window->WantCollapseToggle = false;
6797
6798
        // SIZE
6799
6800
        // Outer Decoration Sizes
6801
        // (we need to clear ScrollbarSize immediatly as CalcWindowAutoFitSize() needs it and can be called from other locations).
6802
107k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
6803
107k
        window->DecoOuterSizeX1 = 0.0f;
6804
107k
        window->DecoOuterSizeX2 = 0.0f;
6805
107k
        window->DecoOuterSizeY1 = window->TitleBarHeight() + window->MenuBarHeight();
6806
107k
        window->DecoOuterSizeY2 = 0.0f;
6807
107k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
6808
6809
        // Calculate auto-fit size, handle automatic resize
6810
107k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
6811
107k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
6812
0
        {
6813
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
6814
0
            if (!window_size_x_set_by_api)
6815
0
            {
6816
0
                window->SizeFull.x = size_auto_fit.x;
6817
0
                use_current_size_for_scrollbar_x = true;
6818
0
            }
6819
0
            if (!window_size_y_set_by_api)
6820
0
            {
6821
0
                window->SizeFull.y = size_auto_fit.y;
6822
0
                use_current_size_for_scrollbar_y = true;
6823
0
            }
6824
0
        }
6825
107k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6826
2
        {
6827
            // Auto-fit may only grow window during the first few frames
6828
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
6829
2
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
6830
2
            {
6831
2
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
6832
2
                use_current_size_for_scrollbar_x = true;
6833
2
            }
6834
2
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
6835
2
            {
6836
2
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
6837
2
                use_current_size_for_scrollbar_y = true;
6838
2
            }
6839
2
            if (!window->Collapsed)
6840
2
                MarkIniSettingsDirty(window);
6841
2
        }
6842
6843
        // Apply minimum/maximum window size constraints and final size
6844
107k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
6845
107k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
6846
6847
        // POSITION
6848
6849
        // Popup latch its initial position, will position itself when it appears next frame
6850
107k
        if (window_just_activated_by_user)
6851
3
        {
6852
3
            window->AutoPosLastDirection = ImGuiDir_None;
6853
3
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
6854
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
6855
3
        }
6856
6857
        // Position child window
6858
107k
        if (flags & ImGuiWindowFlags_ChildWindow)
6859
35.9k
        {
6860
35.9k
            IM_ASSERT(parent_window && parent_window->Active);
6861
35.9k
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
6862
35.9k
            parent_window->DC.ChildWindows.push_back(window);
6863
35.9k
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
6864
35.9k
                window->Pos = parent_window->DC.CursorPos;
6865
35.9k
        }
6866
6867
107k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
6868
107k
        if (window_pos_with_pivot)
6869
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
6870
107k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
6871
0
            window->Pos = FindBestWindowPosForPopup(window);
6872
107k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
6873
0
            window->Pos = FindBestWindowPosForPopup(window);
6874
107k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
6875
0
            window->Pos = FindBestWindowPosForPopup(window);
6876
6877
        // Late create viewport if we don't fit within our current host viewport.
6878
107k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
6879
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
6880
0
            {
6881
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
6882
                //ImGuiViewport* old_viewport = window->Viewport;
6883
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
6884
6885
                // FIXME-DPI
6886
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
6887
0
                SetCurrentViewport(window, window->Viewport);
6888
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6889
0
                SetCurrentWindow(window);
6890
0
            }
6891
6892
107k
        if (window->ViewportOwned)
6893
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
6894
6895
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
6896
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
6897
107k
        ImRect viewport_rect(window->Viewport->GetMainRect());
6898
107k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
6899
107k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
6900
107k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
6901
6902
        // Clamp position/size so window stays visible within its viewport or monitor
6903
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
6904
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
6905
107k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
6906
71.8k
        {
6907
71.8k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
6908
71.8k
            {
6909
71.8k
                ClampWindowPos(window, visibility_rect);
6910
71.8k
            }
6911
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
6912
0
            {
6913
                // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
6914
0
                const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
6915
0
                visibility_rect.Min = monitor->WorkPos + visibility_padding;
6916
0
                visibility_rect.Max = monitor->WorkPos + monitor->WorkSize - visibility_padding;
6917
0
                ClampWindowPos(window, visibility_rect);
6918
0
            }
6919
71.8k
        }
6920
107k
        window->Pos = ImFloor(window->Pos);
6921
6922
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
6923
        // Large values tend to lead to variety of artifacts and are not recommended.
6924
107k
        if (window->ViewportOwned || window->DockIsActive)
6925
0
            window->WindowRounding = 0.0f;
6926
107k
        else
6927
107k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
6928
6929
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
6930
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6931
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
6932
6933
        // Apply window focus (new and reactivated windows are moved to front)
6934
107k
        bool want_focus = false;
6935
107k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
6936
3
        {
6937
3
            if (flags & ImGuiWindowFlags_Popup)
6938
0
                want_focus = true;
6939
3
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
6940
2
                want_focus = true;
6941
3
        }
6942
6943
        // [Test Engine] Register whole window in the item system (before submitting further decorations)
6944
#ifdef IMGUI_ENABLE_TEST_ENGINE
6945
        if (g.TestEngineHookItems)
6946
        {
6947
            IM_ASSERT(window->IDStack.Size == 1);
6948
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
6949
            IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
6950
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
6951
            window->IDStack.Size = 1;
6952
        }
6953
#endif
6954
6955
        // Decide if we are going to handle borders and resize grips
6956
107k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
6957
6958
        // Handle manual resize: Resize Grips, Borders, Gamepad
6959
107k
        int border_held = -1;
6960
107k
        ImU32 resize_grip_col[4] = {};
6961
107k
        const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
6962
107k
        const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6963
107k
        if (handle_borders_and_resize_grips && !window->Collapsed)
6964
107k
            if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
6965
0
                use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
6966
107k
        window->ResizeBorderHeld = (signed char)border_held;
6967
6968
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
6969
107k
        if (window->ViewportOwned)
6970
0
        {
6971
0
            if (!window->Viewport->PlatformRequestMove)
6972
0
                window->Viewport->Pos = window->Pos;
6973
0
            if (!window->Viewport->PlatformRequestResize)
6974
0
                window->Viewport->Size = window->Size;
6975
0
            window->Viewport->UpdateWorkRect();
6976
0
            viewport_rect = window->Viewport->GetMainRect();
6977
0
        }
6978
6979
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
6980
107k
        window->ViewportPos = window->Viewport->Pos;
6981
6982
        // SCROLLBAR VISIBILITY
6983
6984
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
6985
107k
        if (!window->Collapsed)
6986
107k
        {
6987
            // When reading the current size we need to read it after size constraints have been applied.
6988
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
6989
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
6990
107k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
6991
107k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
6992
107k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
6993
107k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
6994
107k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
6995
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
6996
107k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
6997
107k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
6998
107k
            if (window->ScrollbarX && !window->ScrollbarY)
6999
3.42k
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
7000
107k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7001
7002
            // Amend the partially filled window->DecorationXXX values.
7003
107k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7004
107k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7005
107k
        }
7006
7007
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7008
        // Update various regions. Variables they depend on should be set above in this function.
7009
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7010
7011
        // Outer rectangle
7012
        // Not affected by window border size. Used by:
7013
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7014
        // - Begin() initial clipping rect for drawing window background and borders.
7015
        // - Begin() clipping whole child
7016
107k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7017
107k
        const ImRect outer_rect = window->Rect();
7018
107k
        const ImRect title_bar_rect = window->TitleBarRect();
7019
107k
        window->OuterRectClipped = outer_rect;
7020
107k
        if (window->DockIsActive)
7021
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight();
7022
107k
        window->OuterRectClipped.ClipWith(host_rect);
7023
7024
        // Inner rectangle
7025
        // Not affected by window border size. Used by:
7026
        // - InnerClipRect
7027
        // - ScrollToRectEx()
7028
        // - NavUpdatePageUpPageDown()
7029
        // - Scrollbar()
7030
107k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7031
107k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7032
107k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7033
107k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7034
7035
        // Inner clipping rectangle.
7036
        // Will extend a little bit outside the normal work region.
7037
        // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7038
        // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7039
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7040
        // Affected by window/frame border size. Used by:
7041
        // - Begin() initial clip rect
7042
107k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7043
107k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7044
107k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7045
107k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7046
107k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7047
107k
        window->InnerClipRect.ClipWithFull(host_rect);
7048
7049
        // Default item width. Make it proportional to window size if window manually resizes
7050
107k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7051
107k
            window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
7052
0
        else
7053
0
            window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
7054
7055
        // SCROLLING
7056
7057
        // Lock down maximum scrolling
7058
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7059
        // for right/bottom aligned items without creating a scrollbar.
7060
107k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7061
107k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7062
7063
        // Apply scrolling
7064
107k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7065
107k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7066
107k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7067
7068
        // DRAWING
7069
7070
        // Setup draw list and outer clipping rectangle
7071
107k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7072
107k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7073
107k
        PushClipRect(host_rect.Min, host_rect.Max, false);
7074
7075
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7076
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7077
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7078
107k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7079
107k
        if (is_undocked_or_docked_visible)
7080
107k
        {
7081
107k
            bool render_decorations_in_parent = false;
7082
107k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7083
35.9k
            {
7084
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7085
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7086
35.9k
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7087
35.9k
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7088
35.9k
                bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7089
35.9k
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7090
35.9k
                    render_decorations_in_parent = true;
7091
35.9k
            }
7092
107k
            if (render_decorations_in_parent)
7093
35.9k
                window->DrawList = parent_window->DrawList;
7094
7095
            // Handle title bar, scrollbar, resize grips and resize borders
7096
107k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7097
107k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
7098
107k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7099
7100
107k
            if (render_decorations_in_parent)
7101
35.9k
                window->DrawList = &window->DrawListInst;
7102
107k
        }
7103
7104
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7105
7106
        // Work rectangle.
7107
        // Affected by window padding and border size. Used by:
7108
        // - Columns() for right-most edge
7109
        // - TreeNode(), CollapsingHeader() for right-most edge
7110
        // - BeginTabBar() for right-most edge
7111
107k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7112
107k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7113
107k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7114
107k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7115
107k
        window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7116
107k
        window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7117
107k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7118
107k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7119
107k
        window->ParentWorkRect = window->WorkRect;
7120
7121
        // [LEGACY] Content Region
7122
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7123
        // Used by:
7124
        // - Mouse wheel scrolling + many other things
7125
107k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7126
107k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7127
107k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7128
107k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7129
7130
        // Setup drawing context
7131
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7132
107k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7133
107k
        window->DC.GroupOffset.x = 0.0f;
7134
107k
        window->DC.ColumnsOffset.x = 0.0f;
7135
7136
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7137
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7138
107k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7139
107k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7140
107k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7141
107k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7142
107k
        window->DC.CursorPos = window->DC.CursorStartPos;
7143
107k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7144
107k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7145
107k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7146
107k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7147
107k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7148
107k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7149
7150
107k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7151
107k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7152
107k
        window->DC.NavLayersActiveMaskNext = 0x00;
7153
107k
        window->DC.NavIsScrollPushableX = true;
7154
107k
        window->DC.NavHideHighlightOneFrame = false;
7155
107k
        window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7156
7157
107k
        window->DC.MenuBarAppending = false;
7158
107k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7159
107k
        window->DC.TreeDepth = 0;
7160
107k
        window->DC.TreeJumpToParentOnPopMask = 0x00;
7161
107k
        window->DC.ChildWindows.resize(0);
7162
107k
        window->DC.StateStorage = &window->StateStorage;
7163
107k
        window->DC.CurrentColumns = NULL;
7164
107k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7165
107k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7166
7167
107k
        window->DC.ItemWidth = window->ItemWidthDefault;
7168
107k
        window->DC.TextWrapPos = -1.0f; // disabled
7169
107k
        window->DC.ItemWidthStack.resize(0);
7170
107k
        window->DC.TextWrapPosStack.resize(0);
7171
7172
107k
        if (window->AutoFitFramesX > 0)
7173
2
            window->AutoFitFramesX--;
7174
107k
        if (window->AutoFitFramesY > 0)
7175
2
            window->AutoFitFramesY--;
7176
7177
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7178
        // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7179
        // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7180
        // - Position window behind the modal that is not a begin-parent of this window.
7181
107k
        if (want_focus)
7182
2
            FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7183
107k
        if (want_focus && window == g.NavWindow)
7184
2
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7185
7186
        // Close requested by platform window
7187
107k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7188
0
        {
7189
0
            if (!window->DockIsActive || window->DockTabIsVisible)
7190
0
            {
7191
0
                window->Viewport->PlatformRequestClose = false;
7192
0
                g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue.
7193
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' PlatformRequestClose\n", window->Name);
7194
0
                *p_open = false;
7195
0
            }
7196
0
        }
7197
7198
        // Title bar
7199
107k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7200
71.8k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7201
7202
        // Clear hit test shape every frame
7203
107k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7204
7205
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7206
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7207
        // Maybe we can support CTRL+C on every element?
7208
        /*
7209
        //if (g.NavWindow == window && g.ActiveId == 0)
7210
        if (g.ActiveId == window->MoveId)
7211
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7212
                LogToClipboard();
7213
        */
7214
7215
107k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7216
107k
        {
7217
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7218
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7219
107k
            if ((g.MovingWindow == window) && (g.IO.ConfigDockingWithShift == g.IO.KeyShift))
7220
18
                if ((window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7221
18
                    BeginDockableDragDropSource(window);
7222
7223
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7224
107k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7225
45
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7226
27
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7227
27
                        BeginDockableDragDropTarget(window);
7228
107k
        }
7229
7230
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7231
        // This is useful to allow creating context menus on title bar only, etc.
7232
107k
        if (window->DockIsActive)
7233
0
            SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7234
107k
        else
7235
107k
            SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
7236
7237
        // [DEBUG]
7238
107k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7239
107k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7240
0
            DebugLocateItemResolveWithLastItem();
7241
107k
#endif
7242
7243
        // [Test Engine] Register title bar / tab with MoveId.
7244
#ifdef IMGUI_ENABLE_TEST_ENGINE
7245
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7246
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7247
#endif
7248
107k
    }
7249
0
    else
7250
0
    {
7251
        // Append
7252
0
        SetCurrentViewport(window, window->Viewport);
7253
0
        SetCurrentWindow(window);
7254
0
    }
7255
7256
107k
    if (!(flags & ImGuiWindowFlags_DockNodeHost))
7257
107k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7258
7259
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7260
107k
    window->WriteAccessed = false;
7261
107k
    window->BeginCount++;
7262
107k
    g.NextWindowData.ClearFlags();
7263
7264
    // Update visibility
7265
107k
    if (first_begin_of_the_frame)
7266
107k
    {
7267
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7268
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7269
        // This is analogous to regular windows being hidden from one frame.
7270
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7271
107k
        if (window->DockIsActive && !window->DockTabIsVisible)
7272
0
        {
7273
0
            if (window->LastFrameJustFocused == g.FrameCount)
7274
0
                window->HiddenFramesCannotSkipItems = 1;
7275
0
            else
7276
0
                window->HiddenFramesCanSkipItems = 1;
7277
0
        }
7278
7279
107k
        if (flags & ImGuiWindowFlags_ChildWindow)
7280
35.9k
        {
7281
            // Child window can be out of sight and have "negative" clip windows.
7282
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7283
35.9k
            IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || (window->DockIsActive));
7284
35.9k
            if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow??
7285
35.9k
            {
7286
35.9k
                const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7287
35.9k
                if (!g.LogEnabled && !nav_request)
7288
35.9k
                    if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7289
9.83k
                        window->HiddenFramesCanSkipItems = 1;
7290
35.9k
            }
7291
7292
            // Hide along with parent or if parent is collapsed
7293
35.9k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7294
0
                window->HiddenFramesCanSkipItems = 1;
7295
35.9k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7296
1
                window->HiddenFramesCannotSkipItems = 1;
7297
35.9k
        }
7298
7299
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7300
107k
        if (style.Alpha <= 0.0f)
7301
0
            window->HiddenFramesCanSkipItems = 1;
7302
7303
        // Update the Hidden flag
7304
107k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7305
107k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7306
7307
        // Disable inputs for requested number of frames
7308
107k
        if (window->DisableInputsFrames > 0)
7309
0
        {
7310
0
            window->DisableInputsFrames--;
7311
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7312
0
        }
7313
7314
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7315
107k
        bool skip_items = false;
7316
107k
        if (window->Collapsed || !window->Active || hidden_regular)
7317
9.83k
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7318
9.83k
                skip_items = true;
7319
107k
        window->SkipItems = skip_items;
7320
7321
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7322
107k
        if (window->SkipItems)
7323
9.83k
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7324
7325
        // Sanity check: there are two spots which can set Appearing = true
7326
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7327
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7328
107k
        if (window->SkipItems && !window->Appearing)
7329
107k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7330
107k
    }
7331
7332
    // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7333
    // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7334
107k
    if (!window->IsFallbackWindow && ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size)))
7335
0
    {
7336
0
        if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7337
0
        if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7338
0
        return false;
7339
0
    }
7340
7341
107k
    return !window->SkipItems;
7342
107k
}
7343
7344
void ImGui::End()
7345
107k
{
7346
107k
    ImGuiContext& g = *GImGui;
7347
107k
    ImGuiWindow* window = g.CurrentWindow;
7348
7349
    // Error checking: verify that user hasn't called End() too many times!
7350
107k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7351
0
    {
7352
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7353
0
        return;
7354
0
    }
7355
107k
    IM_ASSERT(g.CurrentWindowStack.Size > 0);
7356
7357
    // Error checking: verify that user doesn't directly call End() on a child window.
7358
107k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7359
107k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7360
7361
    // Close anything that is open
7362
107k
    if (window->DC.CurrentColumns)
7363
0
        EndColumns();
7364
107k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost))   // Pop inner window clip rectangle
7365
107k
        PopClipRect();
7366
107k
    PopFocusScope();
7367
7368
    // Stop logging
7369
107k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7370
71.8k
        LogFinish();
7371
7372
107k
    if (window->DC.IsSetPos)
7373
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7374
7375
    // Docking: report contents sizes to parent to allow for auto-resize
7376
107k
    if (window->DockNode && window->DockTabIsVisible)
7377
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7378
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7379
7380
    // Pop from window stack
7381
107k
    g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
7382
107k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7383
0
        g.BeginMenuCount--;
7384
107k
    if (window->Flags & ImGuiWindowFlags_Popup)
7385
0
        g.BeginPopupStack.pop_back();
7386
107k
    g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithContextState(&g);
7387
107k
    g.CurrentWindowStack.pop_back();
7388
107k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7389
107k
    if (g.CurrentWindow)
7390
71.8k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7391
107k
}
7392
7393
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7394
18.3k
{
7395
18.3k
    ImGuiContext& g = *GImGui;
7396
18.3k
    IM_ASSERT(window == window->RootWindow);
7397
7398
18.3k
    const int cur_order = window->FocusOrder;
7399
18.3k
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7400
18.3k
    if (g.WindowsFocusOrder.back() == window)
7401
18.3k
        return;
7402
7403
0
    const int new_order = g.WindowsFocusOrder.Size - 1;
7404
0
    for (int n = cur_order; n < new_order; n++)
7405
0
    {
7406
0
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7407
0
        g.WindowsFocusOrder[n]->FocusOrder--;
7408
0
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7409
0
    }
7410
0
    g.WindowsFocusOrder[new_order] = window;
7411
0
    window->FocusOrder = (short)new_order;
7412
0
}
7413
7414
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7415
18.3k
{
7416
18.3k
    ImGuiContext& g = *GImGui;
7417
18.3k
    ImGuiWindow* current_front_window = g.Windows.back();
7418
18.3k
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7419
18.3k
        return;
7420
0
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7421
0
        if (g.Windows[i] == window)
7422
0
        {
7423
0
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7424
0
            g.Windows[g.Windows.Size - 1] = window;
7425
0
            break;
7426
0
        }
7427
0
}
7428
7429
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7430
0
{
7431
0
    ImGuiContext& g = *GImGui;
7432
0
    if (g.Windows[0] == window)
7433
0
        return;
7434
0
    for (int i = 0; i < g.Windows.Size; i++)
7435
0
        if (g.Windows[i] == window)
7436
0
        {
7437
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7438
0
            g.Windows[0] = window;
7439
0
            break;
7440
0
        }
7441
0
}
7442
7443
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7444
0
{
7445
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7446
0
    ImGuiContext& g = *GImGui;
7447
0
    window = window->RootWindow;
7448
0
    behind_window = behind_window->RootWindow;
7449
0
    int pos_wnd = FindWindowDisplayIndex(window);
7450
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7451
0
    if (pos_wnd < pos_beh)
7452
0
    {
7453
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7454
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7455
0
        g.Windows[pos_beh - 1] = window;
7456
0
    }
7457
0
    else
7458
0
    {
7459
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7460
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7461
0
        g.Windows[pos_beh] = window;
7462
0
    }
7463
0
}
7464
7465
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7466
0
{
7467
0
    ImGuiContext& g = *GImGui;
7468
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
7469
0
}
7470
7471
// Moving window to front of display and set focus (which happens to be back of our sorted list)
7472
void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
7473
25.8k
{
7474
25.8k
    ImGuiContext& g = *GImGui;
7475
7476
    // Modal check?
7477
25.8k
    if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
7478
522
        if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
7479
0
        {
7480
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
7481
0
            if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7482
0
                BringWindowToDisplayBehind(window, blocking_modal); // Still bring to right below modal.
7483
0
            return;
7484
0
        }
7485
7486
    // Find last focused child (if any) and focus it instead.
7487
25.8k
    if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
7488
0
        window = NavRestoreLastChildNavWindow(window);
7489
7490
    // Apply focus
7491
25.8k
    if (g.NavWindow != window)
7492
9.30k
    {
7493
9.30k
        SetNavWindow(window);
7494
9.30k
        if (window && g.NavDisableMouseHover)
7495
922
            g.NavMousePosDirty = true;
7496
9.30k
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7497
9.30k
        g.NavLayer = ImGuiNavLayer_Main;
7498
9.30k
        g.NavFocusScopeId = window ? window->NavRootFocusScopeId : 0;
7499
9.30k
        g.NavIdIsAlive = false;
7500
7501
        // Close popups if any
7502
9.30k
        ClosePopupsOverWindow(window, false);
7503
9.30k
    }
7504
7505
    // Move the root window to the top of the pile
7506
25.8k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7507
25.8k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7508
25.8k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
7509
25.8k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
7510
25.8k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
7511
7512
    // Steal active widgets. Some of the cases it triggers includes:
7513
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7514
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7515
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
7516
25.8k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7517
8
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
7518
5
            ClearActiveID();
7519
7520
    // Passing NULL allow to disable keyboard focus
7521
25.8k
    if (!window)
7522
7.57k
        return;
7523
18.3k
    window->LastFrameJustFocused = g.FrameCount;
7524
7525
    // Select in dock node
7526
18.3k
    if (dock_node && dock_node->TabBar)
7527
0
        dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
7528
7529
    // Bring to front
7530
18.3k
    BringWindowToFocusFront(focus_front_window);
7531
18.3k
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7532
18.3k
        BringWindowToDisplayFront(display_front_window);
7533
18.3k
}
7534
7535
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
7536
0
{
7537
0
    ImGuiContext& g = *GImGui;
7538
0
    int start_idx = g.WindowsFocusOrder.Size - 1;
7539
0
    if (under_this_window != NULL)
7540
0
    {
7541
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7542
0
        int offset = -1;
7543
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7544
0
        {
7545
0
            under_this_window = under_this_window->ParentWindow;
7546
0
            offset = 0;
7547
0
        }
7548
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
7549
0
    }
7550
0
    for (int i = start_idx; i >= 0; i--)
7551
0
    {
7552
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
7553
0
        ImGuiWindow* window = g.WindowsFocusOrder[i];
7554
0
        IM_ASSERT(window == window->RootWindow);
7555
0
        if (window == ignore_window || !window->WasActive)
7556
0
            continue;
7557
0
        if (filter_viewport != NULL && window->Viewport != filter_viewport)
7558
0
            continue;
7559
0
        if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7560
0
        {
7561
            // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
7562
            // This is failing (lagging by one frame) for docked windows.
7563
            // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
7564
            // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
7565
            // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
7566
0
            FocusWindow(window, flags);
7567
0
            return;
7568
0
        }
7569
0
    }
7570
0
    FocusWindow(NULL, flags);
7571
0
}
7572
7573
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7574
void ImGui::SetCurrentFont(ImFont* font)
7575
35.9k
{
7576
35.9k
    ImGuiContext& g = *GImGui;
7577
35.9k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7578
35.9k
    IM_ASSERT(font->Scale > 0.0f);
7579
35.9k
    g.Font = font;
7580
35.9k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7581
35.9k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7582
7583
35.9k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
7584
35.9k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7585
35.9k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7586
35.9k
    g.DrawListSharedData.Font = g.Font;
7587
35.9k
    g.DrawListSharedData.FontSize = g.FontSize;
7588
35.9k
}
7589
7590
void ImGui::PushFont(ImFont* font)
7591
0
{
7592
0
    ImGuiContext& g = *GImGui;
7593
0
    if (!font)
7594
0
        font = GetDefaultFont();
7595
0
    SetCurrentFont(font);
7596
0
    g.FontStack.push_back(font);
7597
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
7598
0
}
7599
7600
void  ImGui::PopFont()
7601
0
{
7602
0
    ImGuiContext& g = *GImGui;
7603
0
    g.CurrentWindow->DrawList->PopTextureID();
7604
0
    g.FontStack.pop_back();
7605
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7606
0
}
7607
7608
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7609
35.9k
{
7610
35.9k
    ImGuiContext& g = *GImGui;
7611
35.9k
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
7612
35.9k
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7613
35.9k
    if (enabled)
7614
0
        item_flags |= option;
7615
35.9k
    else
7616
35.9k
        item_flags &= ~option;
7617
35.9k
    g.CurrentItemFlags = item_flags;
7618
35.9k
    g.ItemFlagsStack.push_back(item_flags);
7619
35.9k
}
7620
7621
void ImGui::PopItemFlag()
7622
35.9k
{
7623
35.9k
    ImGuiContext& g = *GImGui;
7624
35.9k
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7625
35.9k
    g.ItemFlagsStack.pop_back();
7626
35.9k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7627
35.9k
}
7628
7629
// BeginDisabled()/EndDisabled()
7630
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
7631
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7632
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7633
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
7634
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7635
void ImGui::BeginDisabled(bool disabled)
7636
0
{
7637
0
    ImGuiContext& g = *GImGui;
7638
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7639
0
    if (!was_disabled && disabled)
7640
0
    {
7641
0
        g.DisabledAlphaBackup = g.Style.Alpha;
7642
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7643
0
    }
7644
0
    if (was_disabled || disabled)
7645
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7646
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
7647
0
    g.DisabledStackSize++;
7648
0
}
7649
7650
void ImGui::EndDisabled()
7651
0
{
7652
0
    ImGuiContext& g = *GImGui;
7653
0
    IM_ASSERT(g.DisabledStackSize > 0);
7654
0
    g.DisabledStackSize--;
7655
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7656
    //PopItemFlag();
7657
0
    g.ItemFlagsStack.pop_back();
7658
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7659
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7660
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7661
0
}
7662
7663
void ImGui::PushTabStop(bool tab_stop)
7664
35.9k
{
7665
35.9k
    PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);
7666
35.9k
}
7667
7668
void ImGui::PopTabStop()
7669
35.9k
{
7670
35.9k
    PopItemFlag();
7671
35.9k
}
7672
7673
void ImGui::PushButtonRepeat(bool repeat)
7674
0
{
7675
0
    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
7676
0
}
7677
7678
void ImGui::PopButtonRepeat()
7679
0
{
7680
0
    PopItemFlag();
7681
0
}
7682
7683
void ImGui::PushTextWrapPos(float wrap_pos_x)
7684
0
{
7685
0
    ImGuiWindow* window = GetCurrentWindow();
7686
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
7687
0
    window->DC.TextWrapPos = wrap_pos_x;
7688
0
}
7689
7690
void ImGui::PopTextWrapPos()
7691
0
{
7692
0
    ImGuiWindow* window = GetCurrentWindow();
7693
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7694
0
    window->DC.TextWrapPosStack.pop_back();
7695
0
}
7696
7697
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
7698
0
{
7699
0
    ImGuiWindow* last_window = NULL;
7700
0
    while (last_window != window)
7701
0
    {
7702
0
        last_window = window;
7703
0
        window = window->RootWindow;
7704
0
        if (popup_hierarchy)
7705
0
            window = window->RootWindowPopupTree;
7706
0
    if (dock_hierarchy)
7707
0
      window = window->RootWindowDockTree;
7708
0
  }
7709
0
    return window;
7710
0
}
7711
7712
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
7713
0
{
7714
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
7715
0
    if (window_root == potential_parent)
7716
0
        return true;
7717
0
    while (window != NULL)
7718
0
    {
7719
0
        if (window == potential_parent)
7720
0
            return true;
7721
0
        if (window == window_root) // end of chain
7722
0
            return false;
7723
0
        window = window->ParentWindow;
7724
0
    }
7725
0
    return false;
7726
0
}
7727
7728
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
7729
0
{
7730
0
    if (window->RootWindow == potential_parent)
7731
0
        return true;
7732
0
    while (window != NULL)
7733
0
    {
7734
0
        if (window == potential_parent)
7735
0
            return true;
7736
0
        window = window->ParentWindowInBeginStack;
7737
0
    }
7738
0
    return false;
7739
0
}
7740
7741
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
7742
0
{
7743
0
    ImGuiContext& g = *GImGui;
7744
7745
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
7746
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
7747
0
    if (display_layer_delta != 0)
7748
0
        return display_layer_delta > 0;
7749
7750
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
7751
0
    {
7752
0
        ImGuiWindow* candidate_window = g.Windows[i];
7753
0
        if (candidate_window == potential_above)
7754
0
            return true;
7755
0
        if (candidate_window == potential_below)
7756
0
            return false;
7757
0
    }
7758
0
    return false;
7759
0
}
7760
7761
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
7762
61.1k
{
7763
61.1k
    IM_ASSERT((flags & (ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled)) == 0);   // Flags not supported by this function
7764
61.1k
    ImGuiContext& g = *GImGui;
7765
61.1k
    ImGuiWindow* ref_window = g.HoveredWindow;
7766
61.1k
    ImGuiWindow* cur_window = g.CurrentWindow;
7767
61.1k
    if (ref_window == NULL)
7768
59.9k
        return false;
7769
7770
1.25k
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
7771
1.25k
    {
7772
1.25k
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
7773
1.25k
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
7774
1.25k
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
7775
1.25k
        if (flags & ImGuiHoveredFlags_RootWindow)
7776
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7777
7778
1.25k
        bool result;
7779
1.25k
        if (flags & ImGuiHoveredFlags_ChildWindows)
7780
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7781
1.25k
        else
7782
1.25k
            result = (ref_window == cur_window);
7783
1.25k
        if (!result)
7784
1.25k
            return false;
7785
1.25k
    }
7786
7787
3
    if (!IsWindowContentHoverable(ref_window, flags))
7788
0
        return false;
7789
3
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
7790
3
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
7791
0
            return false;
7792
3
    return true;
7793
3
}
7794
7795
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
7796
70.3k
{
7797
70.3k
    ImGuiContext& g = *GImGui;
7798
70.3k
    ImGuiWindow* ref_window = g.NavWindow;
7799
70.3k
    ImGuiWindow* cur_window = g.CurrentWindow;
7800
7801
70.3k
    if (ref_window == NULL)
7802
14.8k
        return false;
7803
55.4k
    if (flags & ImGuiFocusedFlags_AnyWindow)
7804
0
        return true;
7805
7806
55.4k
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
7807
55.4k
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
7808
55.4k
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
7809
55.4k
    if (flags & ImGuiHoveredFlags_RootWindow)
7810
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7811
7812
55.4k
    if (flags & ImGuiHoveredFlags_ChildWindows)
7813
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7814
55.4k
    else
7815
55.4k
        return (ref_window == cur_window);
7816
55.4k
}
7817
7818
ImGuiID ImGui::GetWindowDockID()
7819
0
{
7820
0
    ImGuiContext& g = *GImGui;
7821
0
    return g.CurrentWindow->DockId;
7822
0
}
7823
7824
bool ImGui::IsWindowDocked()
7825
0
{
7826
0
    ImGuiContext& g = *GImGui;
7827
0
    return g.CurrentWindow->DockIsActive;
7828
0
}
7829
7830
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
7831
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
7832
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
7833
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
7834
0
{
7835
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
7836
0
}
7837
7838
float ImGui::GetWindowWidth()
7839
18.0k
{
7840
18.0k
    ImGuiWindow* window = GImGui->CurrentWindow;
7841
18.0k
    return window->Size.x;
7842
18.0k
}
7843
7844
float ImGui::GetWindowHeight()
7845
18.9k
{
7846
18.9k
    ImGuiWindow* window = GImGui->CurrentWindow;
7847
18.9k
    return window->Size.y;
7848
18.9k
}
7849
7850
ImVec2 ImGui::GetWindowPos()
7851
0
{
7852
0
    ImGuiContext& g = *GImGui;
7853
0
    ImGuiWindow* window = g.CurrentWindow;
7854
0
    return window->Pos;
7855
0
}
7856
7857
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
7858
8
{
7859
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7860
8
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
7861
0
        return;
7862
7863
8
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7864
8
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7865
8
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
7866
7867
    // Set
7868
8
    const ImVec2 old_pos = window->Pos;
7869
8
    window->Pos = ImFloor(pos);
7870
8
    ImVec2 offset = window->Pos - old_pos;
7871
8
    if (offset.x == 0.0f && offset.y == 0.0f)
7872
0
        return;
7873
8
    MarkIniSettingsDirty(window);
7874
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
7875
8
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
7876
8
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
7877
8
    window->DC.IdealMaxPos += offset;
7878
8
    window->DC.CursorStartPos += offset;
7879
8
}
7880
7881
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
7882
0
{
7883
0
    ImGuiWindow* window = GetCurrentWindowRead();
7884
0
    SetWindowPos(window, pos, cond);
7885
0
}
7886
7887
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
7888
0
{
7889
0
    if (ImGuiWindow* window = FindWindowByName(name))
7890
0
        SetWindowPos(window, pos, cond);
7891
0
}
7892
7893
ImVec2 ImGui::GetWindowSize()
7894
0
{
7895
0
    ImGuiWindow* window = GetCurrentWindowRead();
7896
0
    return window->Size;
7897
0
}
7898
7899
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
7900
71.8k
{
7901
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7902
71.8k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
7903
35.9k
        return;
7904
7905
35.9k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7906
35.9k
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7907
7908
    // Set
7909
35.9k
    ImVec2 old_size = window->SizeFull;
7910
35.9k
    window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
7911
35.9k
    window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
7912
35.9k
    if (size.x <= 0.0f)
7913
0
        window->AutoFitOnlyGrows = false;
7914
35.9k
    else
7915
35.9k
        window->SizeFull.x = IM_FLOOR(size.x);
7916
35.9k
    if (size.y <= 0.0f)
7917
0
        window->AutoFitOnlyGrows = false;
7918
35.9k
    else
7919
35.9k
        window->SizeFull.y = IM_FLOOR(size.y);
7920
35.9k
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
7921
6.57k
        MarkIniSettingsDirty(window);
7922
35.9k
}
7923
7924
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
7925
0
{
7926
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
7927
0
}
7928
7929
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
7930
0
{
7931
0
    if (ImGuiWindow* window = FindWindowByName(name))
7932
0
        SetWindowSize(window, size, cond);
7933
0
}
7934
7935
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
7936
0
{
7937
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7938
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
7939
0
        return;
7940
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7941
7942
    // Set
7943
0
    window->Collapsed = collapsed;
7944
0
}
7945
7946
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
7947
0
{
7948
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
7949
0
    window->HitTestHoleSize = ImVec2ih(size);
7950
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
7951
0
}
7952
7953
void ImGui::SetWindowHiddendAndSkipItemsForCurrentFrame(ImGuiWindow* window)
7954
0
{
7955
0
    window->Hidden = window->SkipItems = true;
7956
0
    window->HiddenFramesCanSkipItems = 1;
7957
0
}
7958
7959
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
7960
0
{
7961
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
7962
0
}
7963
7964
bool ImGui::IsWindowCollapsed()
7965
0
{
7966
0
    ImGuiWindow* window = GetCurrentWindowRead();
7967
0
    return window->Collapsed;
7968
0
}
7969
7970
bool ImGui::IsWindowAppearing()
7971
0
{
7972
0
    ImGuiWindow* window = GetCurrentWindowRead();
7973
0
    return window->Appearing;
7974
0
}
7975
7976
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
7977
0
{
7978
0
    if (ImGuiWindow* window = FindWindowByName(name))
7979
0
        SetWindowCollapsed(window, collapsed, cond);
7980
0
}
7981
7982
void ImGui::SetWindowFocus()
7983
18.0k
{
7984
18.0k
    FocusWindow(GImGui->CurrentWindow);
7985
18.0k
}
7986
7987
void ImGui::SetWindowFocus(const char* name)
7988
0
{
7989
0
    if (name)
7990
0
    {
7991
0
        if (ImGuiWindow* window = FindWindowByName(name))
7992
0
            FocusWindow(window);
7993
0
    }
7994
0
    else
7995
0
    {
7996
0
        FocusWindow(NULL);
7997
0
    }
7998
0
}
7999
8000
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8001
0
{
8002
0
    ImGuiContext& g = *GImGui;
8003
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8004
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8005
0
    g.NextWindowData.PosVal = pos;
8006
0
    g.NextWindowData.PosPivotVal = pivot;
8007
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8008
0
    g.NextWindowData.PosUndock = true;
8009
0
}
8010
8011
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8012
71.8k
{
8013
71.8k
    ImGuiContext& g = *GImGui;
8014
71.8k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8015
71.8k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8016
71.8k
    g.NextWindowData.SizeVal = size;
8017
71.8k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8018
71.8k
}
8019
8020
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8021
0
{
8022
0
    ImGuiContext& g = *GImGui;
8023
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8024
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8025
0
    g.NextWindowData.SizeCallback = custom_callback;
8026
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8027
0
}
8028
8029
// Content size = inner scrollable rectangle, padded with WindowPadding.
8030
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8031
void ImGui::SetNextWindowContentSize(const ImVec2& size)
8032
0
{
8033
0
    ImGuiContext& g = *GImGui;
8034
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8035
0
    g.NextWindowData.ContentSizeVal = ImFloor(size);
8036
0
}
8037
8038
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8039
0
{
8040
0
    ImGuiContext& g = *GImGui;
8041
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8042
0
    g.NextWindowData.ScrollVal = scroll;
8043
0
}
8044
8045
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8046
0
{
8047
0
    ImGuiContext& g = *GImGui;
8048
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8049
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8050
0
    g.NextWindowData.CollapsedVal = collapsed;
8051
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8052
0
}
8053
8054
void ImGui::SetNextWindowFocus()
8055
0
{
8056
0
    ImGuiContext& g = *GImGui;
8057
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8058
0
}
8059
8060
void ImGui::SetNextWindowBgAlpha(float alpha)
8061
0
{
8062
0
    ImGuiContext& g = *GImGui;
8063
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8064
0
    g.NextWindowData.BgAlphaVal = alpha;
8065
0
}
8066
8067
void ImGui::SetNextWindowViewport(ImGuiID id)
8068
0
{
8069
0
    ImGuiContext& g = *GImGui;
8070
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8071
0
    g.NextWindowData.ViewportId = id;
8072
0
}
8073
8074
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8075
0
{
8076
0
    ImGuiContext& g = *GImGui;
8077
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8078
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8079
0
    g.NextWindowData.DockId = id;
8080
0
}
8081
8082
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8083
0
{
8084
0
    ImGuiContext& g = *GImGui;
8085
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8086
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8087
0
    g.NextWindowData.WindowClass = *window_class;
8088
0
}
8089
8090
ImDrawList* ImGui::GetWindowDrawList()
8091
35.9k
{
8092
35.9k
    ImGuiWindow* window = GetCurrentWindow();
8093
35.9k
    return window->DrawList;
8094
35.9k
}
8095
8096
float ImGui::GetWindowDpiScale()
8097
0
{
8098
0
    ImGuiContext& g = *GImGui;
8099
0
    return g.CurrentDpiScale;
8100
0
}
8101
8102
ImGuiViewport* ImGui::GetWindowViewport()
8103
0
{
8104
0
    ImGuiContext& g = *GImGui;
8105
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8106
0
    return g.CurrentViewport;
8107
0
}
8108
8109
ImFont* ImGui::GetFont()
8110
35.9M
{
8111
35.9M
    return GImGui->Font;
8112
35.9M
}
8113
8114
float ImGui::GetFontSize()
8115
36.6M
{
8116
36.6M
    return GImGui->FontSize;
8117
36.6M
}
8118
8119
ImVec2 ImGui::GetFontTexUvWhitePixel()
8120
0
{
8121
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
8122
0
}
8123
8124
void ImGui::SetWindowFontScale(float scale)
8125
0
{
8126
0
    IM_ASSERT(scale > 0.0f);
8127
0
    ImGuiContext& g = *GImGui;
8128
0
    ImGuiWindow* window = GetCurrentWindow();
8129
0
    window->FontWindowScale = scale;
8130
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8131
0
}
8132
8133
void ImGui::PushFocusScope(ImGuiID id)
8134
107k
{
8135
107k
    ImGuiContext& g = *GImGui;
8136
107k
    g.FocusScopeStack.push_back(id);
8137
107k
    g.CurrentFocusScopeId = id;
8138
107k
}
8139
8140
void ImGui::PopFocusScope()
8141
107k
{
8142
107k
    ImGuiContext& g = *GImGui;
8143
107k
    IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
8144
107k
    g.FocusScopeStack.pop_back();
8145
107k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back() : 0;
8146
107k
}
8147
8148
// Focus = move navigation cursor, set scrolling, set focus window.
8149
void ImGui::FocusItem()
8150
0
{
8151
0
    ImGuiContext& g = *GImGui;
8152
0
    ImGuiWindow* window = g.CurrentWindow;
8153
0
    IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8154
0
    if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8155
0
    {
8156
0
        IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8157
0
        return;
8158
0
    }
8159
8160
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_Tabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSelect;
8161
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8162
0
    SetNavWindow(window);
8163
0
    NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
8164
0
    NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8165
0
}
8166
8167
void ImGui::ActivateItemByID(ImGuiID id)
8168
0
{
8169
0
    ImGuiContext& g = *GImGui;
8170
0
    g.NavNextActivateId = id;
8171
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8172
0
}
8173
8174
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8175
// But ActivateItem() should function without altering scroll/focus?
8176
void ImGui::SetKeyboardFocusHere(int offset)
8177
0
{
8178
0
    ImGuiContext& g = *GImGui;
8179
0
    ImGuiWindow* window = g.CurrentWindow;
8180
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8181
0
    IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8182
8183
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8184
    // When we refactor this function into ActivateItem() we may want to make this an option.
8185
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8186
    // is also automatically dropped in the event g.ActiveId is stolen.
8187
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8188
0
    {
8189
0
        IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8190
0
        return;
8191
0
    }
8192
8193
0
    SetNavWindow(window);
8194
8195
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_Tabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi;
8196
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8197
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8198
0
    if (offset == -1)
8199
0
    {
8200
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8201
0
    }
8202
0
    else
8203
0
    {
8204
0
        g.NavTabbingDir = 1;
8205
0
        g.NavTabbingCounter = offset + 1;
8206
0
    }
8207
0
}
8208
8209
void ImGui::SetItemDefaultFocus()
8210
0
{
8211
0
    ImGuiContext& g = *GImGui;
8212
0
    ImGuiWindow* window = g.CurrentWindow;
8213
0
    if (!window->Appearing)
8214
0
        return;
8215
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8216
0
        return;
8217
8218
0
    g.NavInitRequest = false;
8219
0
    NavApplyItemToResult(&g.NavInitResult);
8220
0
    NavUpdateAnyRequestFlag();
8221
8222
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8223
0
    if (!window->ClipRect.Contains(g.LastItemData.Rect))
8224
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8225
0
}
8226
8227
void ImGui::SetStateStorage(ImGuiStorage* tree)
8228
0
{
8229
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8230
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8231
0
}
8232
8233
ImGuiStorage* ImGui::GetStateStorage()
8234
0
{
8235
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8236
0
    return window->DC.StateStorage;
8237
0
}
8238
8239
void ImGui::PushID(const char* str_id)
8240
35.9k
{
8241
35.9k
    ImGuiContext& g = *GImGui;
8242
35.9k
    ImGuiWindow* window = g.CurrentWindow;
8243
35.9k
    ImGuiID id = window->GetID(str_id);
8244
35.9k
    window->IDStack.push_back(id);
8245
35.9k
}
8246
8247
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8248
0
{
8249
0
    ImGuiContext& g = *GImGui;
8250
0
    ImGuiWindow* window = g.CurrentWindow;
8251
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8252
0
    window->IDStack.push_back(id);
8253
0
}
8254
8255
void ImGui::PushID(const void* ptr_id)
8256
0
{
8257
0
    ImGuiContext& g = *GImGui;
8258
0
    ImGuiWindow* window = g.CurrentWindow;
8259
0
    ImGuiID id = window->GetID(ptr_id);
8260
0
    window->IDStack.push_back(id);
8261
0
}
8262
8263
void ImGui::PushID(int int_id)
8264
0
{
8265
0
    ImGuiContext& g = *GImGui;
8266
0
    ImGuiWindow* window = g.CurrentWindow;
8267
0
    ImGuiID id = window->GetID(int_id);
8268
0
    window->IDStack.push_back(id);
8269
0
}
8270
8271
// Push a given id value ignoring the ID stack as a seed.
8272
void ImGui::PushOverrideID(ImGuiID id)
8273
0
{
8274
0
    ImGuiContext& g = *GImGui;
8275
0
    ImGuiWindow* window = g.CurrentWindow;
8276
0
    if (g.DebugHookIdInfo == id)
8277
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8278
0
    window->IDStack.push_back(id);
8279
0
}
8280
8281
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8282
// (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level.
8283
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8284
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8285
0
{
8286
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8287
0
    ImGuiContext& g = *GImGui;
8288
0
    if (g.DebugHookIdInfo == id)
8289
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8290
0
    return id;
8291
0
}
8292
8293
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8294
0
{
8295
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8296
0
    ImGuiContext& g = *GImGui;
8297
0
    if (g.DebugHookIdInfo == id)
8298
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8299
0
    return id;
8300
0
}
8301
8302
void ImGui::PopID()
8303
35.9k
{
8304
35.9k
    ImGuiWindow* window = GImGui->CurrentWindow;
8305
35.9k
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8306
35.9k
    window->IDStack.pop_back();
8307
35.9k
}
8308
8309
ImGuiID ImGui::GetID(const char* str_id)
8310
0
{
8311
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8312
0
    return window->GetID(str_id);
8313
0
}
8314
8315
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8316
0
{
8317
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8318
0
    return window->GetID(str_id_begin, str_id_end);
8319
0
}
8320
8321
ImGuiID ImGui::GetID(const void* ptr_id)
8322
0
{
8323
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8324
0
    return window->GetID(ptr_id);
8325
0
}
8326
8327
bool ImGui::IsRectVisible(const ImVec2& size)
8328
0
{
8329
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8330
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8331
0
}
8332
8333
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8334
0
{
8335
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8336
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8337
0
}
8338
8339
8340
//-----------------------------------------------------------------------------
8341
// [SECTION] INPUTS
8342
//-----------------------------------------------------------------------------
8343
// - GetKeyData() [Internal]
8344
// - GetKeyIndex() [Internal]
8345
// - GetKeyName()
8346
// - GetKeyChordName() [Internal]
8347
// - CalcTypematicRepeatAmount() [Internal]
8348
// - GetTypematicRepeatRate() [Internal]
8349
// - GetKeyPressedAmount() [Internal]
8350
// - GetKeyMagnitude2d() [Internal]
8351
//-----------------------------------------------------------------------------
8352
// - UpdateKeyRoutingTable() [Internal]
8353
// - GetRoutingIdFromOwnerId() [Internal]
8354
// - GetShortcutRoutingData() [Internal]
8355
// - CalcRoutingScore() [Internal]
8356
// - SetShortcutRouting() [Internal]
8357
// - TestShortcutRouting() [Internal]
8358
//-----------------------------------------------------------------------------
8359
// - IsKeyDown()
8360
// - IsKeyPressed()
8361
// - IsKeyReleased()
8362
//-----------------------------------------------------------------------------
8363
// - IsMouseDown()
8364
// - IsMouseClicked()
8365
// - IsMouseReleased()
8366
// - IsMouseDoubleClicked()
8367
// - GetMouseClickedCount()
8368
// - IsMouseHoveringRect() [Internal]
8369
// - IsMouseDragPastThreshold() [Internal]
8370
// - IsMouseDragging()
8371
// - GetMousePos()
8372
// - GetMousePosOnOpeningCurrentPopup()
8373
// - IsMousePosValid()
8374
// - IsAnyMouseDown()
8375
// - GetMouseDragDelta()
8376
// - ResetMouseDragDelta()
8377
// - GetMouseCursor()
8378
// - SetMouseCursor()
8379
//-----------------------------------------------------------------------------
8380
// - UpdateAliasKey()
8381
// - GetMergedModsFromKeys()
8382
// - UpdateKeyboardInputs()
8383
// - UpdateMouseInputs()
8384
//-----------------------------------------------------------------------------
8385
// - LockWheelingWindow [Internal]
8386
// - FindBestWheelingWindow [Internal]
8387
// - UpdateMouseWheel() [Internal]
8388
//-----------------------------------------------------------------------------
8389
// - SetNextFrameWantCaptureKeyboard()
8390
// - SetNextFrameWantCaptureMouse()
8391
//-----------------------------------------------------------------------------
8392
// - GetInputSourceName() [Internal]
8393
// - DebugPrintInputEvent() [Internal]
8394
// - UpdateInputEvents() [Internal]
8395
//-----------------------------------------------------------------------------
8396
// - GetKeyOwner() [Internal]
8397
// - TestKeyOwner() [Internal]
8398
// - SetKeyOwner() [Internal]
8399
// - SetItemKeyOwner() [Internal]
8400
// - Shortcut() [Internal]
8401
//-----------------------------------------------------------------------------
8402
8403
ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
8404
1.47M
{
8405
1.47M
    ImGuiContext& g = *ctx;
8406
8407
    // Special storage location for mods
8408
1.47M
    if (key & ImGuiMod_Mask_)
8409
323k
        key = ConvertSingleModFlagToKey(ctx, key);
8410
8411
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8412
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8413
    if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
8414
        key = (ImGuiKey)g.IO.KeyMap[key];  // Remap native->imgui or imgui->native
8415
#else
8416
1.47M
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8417
1.47M
#endif
8418
1.47M
    return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
8419
1.47M
}
8420
8421
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8422
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8423
{
8424
    ImGuiContext& g = *GImGui;
8425
    IM_ASSERT(IsNamedKey(key));
8426
    const ImGuiKeyData* key_data = GetKeyData(key);
8427
    return (ImGuiKey)(key_data - g.IO.KeysData);
8428
}
8429
#endif
8430
8431
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8432
static const char* const GKeyNames[] =
8433
{
8434
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8435
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8436
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8437
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8438
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8439
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8440
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8441
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8442
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8443
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8444
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8445
    "GamepadStart", "GamepadBack",
8446
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8447
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8448
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8449
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8450
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8451
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8452
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8453
};
8454
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8455
8456
const char* ImGui::GetKeyName(ImGuiKey key)
8457
0
{
8458
0
    ImGuiContext& g = *GImGui;
8459
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8460
0
    IM_ASSERT((IsNamedKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8461
#else
8462
    if (IsLegacyKey(key))
8463
    {
8464
        if (g.IO.KeyMap[key] == -1)
8465
            return "N/A";
8466
        IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
8467
        key = (ImGuiKey)g.IO.KeyMap[key];
8468
    }
8469
#endif
8470
0
    if (key == ImGuiKey_None)
8471
0
        return "None";
8472
0
    if (key & ImGuiMod_Mask_)
8473
0
        key = ConvertSingleModFlagToKey(&g, key);
8474
0
    if (!IsNamedKey(key))
8475
0
        return "Unknown";
8476
8477
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8478
0
}
8479
8480
// ImGuiMod_Shortcut is translated to either Ctrl or Super.
8481
void ImGui::GetKeyChordName(ImGuiKeyChord key_chord, char* out_buf, int out_buf_size)
8482
0
{
8483
0
    ImGuiContext& g = *GImGui;
8484
0
    if (key_chord & ImGuiMod_Shortcut)
8485
0
        key_chord = ConvertShortcutMod(key_chord);
8486
0
    ImFormatString(out_buf, (size_t)out_buf_size, "%s%s%s%s%s",
8487
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8488
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8489
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8490
0
        (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
8491
0
        GetKeyName((ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
8492
0
}
8493
8494
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8495
// t1 = current time (e.g.: g.Time)
8496
// An event is triggered at:
8497
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
8498
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8499
19.6k
{
8500
19.6k
    if (t1 == 0.0f)
8501
0
        return 1;
8502
19.6k
    if (t0 >= t1)
8503
0
        return 0;
8504
19.6k
    if (repeat_rate <= 0.0f)
8505
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
8506
19.6k
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8507
19.6k
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8508
19.6k
    const int count = count_t1 - count_t0;
8509
19.6k
    return count;
8510
19.6k
}
8511
8512
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8513
38.4k
{
8514
38.4k
    ImGuiContext& g = *GImGui;
8515
38.4k
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
8516
38.4k
    {
8517
5.08k
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8518
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8519
33.3k
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8520
38.4k
    }
8521
38.4k
}
8522
8523
// Return value representing the number of presses in the last time period, for the given repeat rate
8524
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8525
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8526
19.6k
{
8527
19.6k
    ImGuiContext& g = *GImGui;
8528
19.6k
    const ImGuiKeyData* key_data = GetKeyData(key);
8529
19.6k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8530
0
        return 0;
8531
19.6k
    const float t = key_data->DownDuration;
8532
19.6k
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
8533
19.6k
}
8534
8535
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8536
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8537
0
{
8538
0
    return ImVec2(
8539
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
8540
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
8541
0
}
8542
8543
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
8544
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
8545
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
8546
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
8547
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
8548
35.9k
{
8549
35.9k
    ImGuiContext& g = *GImGui;
8550
35.9k
    rt->EntriesNext.resize(0);
8551
5.06M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8552
5.02M
    {
8553
5.02M
        const int new_routing_start_idx = rt->EntriesNext.Size;
8554
5.02M
        ImGuiKeyRoutingData* routing_entry;
8555
5.02M
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
8556
0
        {
8557
0
            routing_entry = &rt->Entries[old_routing_idx];
8558
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
8559
0
            routing_entry->RoutingNext = ImGuiKeyOwner_None;
8560
0
            routing_entry->RoutingNextScore = 255;
8561
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_None)
8562
0
                continue;
8563
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
8564
8565
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
8566
0
            if (routing_entry->Mods == g.IO.KeyMods)
8567
0
            {
8568
0
                ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
8569
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
8570
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
8571
0
            }
8572
0
        }
8573
8574
        // Rewrite linked-list
8575
5.02M
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
8576
5.02M
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
8577
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
8578
5.02M
    }
8579
35.9k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
8580
35.9k
}
8581
8582
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
8583
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
8584
0
{
8585
0
    ImGuiContext& g = *GImGui;
8586
0
    return (owner_id != ImGuiKeyOwner_None && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
8587
0
}
8588
8589
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
8590
0
{
8591
    // Majority of shortcuts will be Key + any number of Mods
8592
    // We accept _Single_ mod with ImGuiKey_None.
8593
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
8594
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
8595
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
8596
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
8597
0
    ImGuiContext& g = *GImGui;
8598
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
8599
0
    ImGuiKeyRoutingData* routing_data;
8600
0
    if (key_chord & ImGuiMod_Shortcut)
8601
0
        key_chord = ConvertShortcutMod(key_chord);
8602
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8603
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
8604
0
    if (key == ImGuiKey_None)
8605
0
        key = ConvertSingleModFlagToKey(&g, mods);
8606
0
    IM_ASSERT(IsNamedKey(key));
8607
8608
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
8609
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
8610
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
8611
0
    {
8612
0
        routing_data = &rt->Entries[idx];
8613
0
        if (routing_data->Mods == mods)
8614
0
            return routing_data;
8615
0
    }
8616
8617
    // Add to linked-list
8618
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
8619
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
8620
0
    routing_data = &rt->Entries[routing_data_idx];
8621
0
    routing_data->Mods = (ImU16)mods;
8622
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
8623
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
8624
0
    return routing_data;
8625
0
}
8626
8627
// Current score encoding (lower is highest priority):
8628
//  -   0: ImGuiInputFlags_RouteGlobalHigh
8629
//  -   1: ImGuiInputFlags_RouteFocused (if item active)
8630
//  -   2: ImGuiInputFlags_RouteGlobal
8631
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
8632
//  - 254: ImGuiInputFlags_RouteGlobalLow
8633
//  - 255: never route
8634
// 'flags' should include an explicit routing policy
8635
static int CalcRoutingScore(ImGuiWindow* location, ImGuiID owner_id, ImGuiInputFlags flags)
8636
0
{
8637
0
    if (flags & ImGuiInputFlags_RouteFocused)
8638
0
    {
8639
0
        ImGuiContext& g = *GImGui;
8640
0
        ImGuiWindow* focused = g.NavWindow;
8641
8642
        // ActiveID gets top priority
8643
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
8644
0
        if (owner_id != 0 && g.ActiveId == owner_id)
8645
0
            return 1;
8646
8647
        // Score based on distance to focused window (lower is better)
8648
        // Assuming both windows are submitting a routing request,
8649
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
8650
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
8651
        // Assuming only WindowA is submitting a routing request,
8652
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
8653
0
        if (focused != NULL && focused->RootWindow == location->RootWindow)
8654
0
            for (int next_score = 3; focused != NULL; next_score++)
8655
0
            {
8656
0
                if (focused == location)
8657
0
                {
8658
0
                    IM_ASSERT(next_score < 255);
8659
0
                    return next_score;
8660
0
                }
8661
0
                focused = (focused->RootWindow != focused) ? focused->ParentWindow : NULL; // FIXME: This could be later abstracted as a focus path
8662
0
            }
8663
0
        return 255;
8664
0
    }
8665
8666
    // ImGuiInputFlags_RouteGlobalHigh is default, so calls without flags are not conditional
8667
0
    if (flags & ImGuiInputFlags_RouteGlobal)
8668
0
        return 2;
8669
0
    if (flags & ImGuiInputFlags_RouteGlobalLow)
8670
0
        return 254;
8671
0
    return 0;
8672
0
}
8673
8674
// Request a desired route for an input chord (key + mods).
8675
// Return true if the route is available this frame.
8676
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
8677
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
8678
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
8679
// - Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
8680
// - Using 'owner_id == ImGuiKeyOwner_None': allows disabling/locking a shortcut.
8681
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
8682
71.8k
{
8683
71.8k
    ImGuiContext& g = *GImGui;
8684
71.8k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
8685
0
        flags |= ImGuiInputFlags_RouteGlobalHigh; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
8686
71.8k
    else
8687
71.8k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteMask_)); // Check that only 1 routing flag is used
8688
8689
71.8k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
8690
0
        if (g.NavWindow == NULL)
8691
0
            return false;
8692
71.8k
    if (flags & ImGuiInputFlags_RouteAlways)
8693
71.8k
        return true;
8694
8695
0
    const int score = CalcRoutingScore(g.CurrentWindow, owner_id, flags);
8696
0
    if (score == 255)
8697
0
        return false;
8698
8699
    // Submit routing for NEXT frame (assuming score is sufficient)
8700
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
8701
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
8702
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8703
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
8704
0
    if (score < routing_data->RoutingNextScore)
8705
0
    {
8706
0
        routing_data->RoutingNext = routing_id;
8707
0
        routing_data->RoutingNextScore = (ImU8)score;
8708
0
    }
8709
8710
    // Return routing state for CURRENT frame
8711
0
    return routing_data->RoutingCurr == routing_id;
8712
0
}
8713
8714
// Currently unused by core (but used by tests)
8715
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
8716
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
8717
0
{
8718
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8719
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
8720
0
    return routing_data->RoutingCurr == routing_id;
8721
0
}
8722
8723
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
8724
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
8725
bool ImGui::IsKeyDown(ImGuiKey key)
8726
544k
{
8727
544k
    return IsKeyDown(key, ImGuiKeyOwner_Any);
8728
544k
}
8729
8730
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
8731
598k
{
8732
598k
    const ImGuiKeyData* key_data = GetKeyData(key);
8733
598k
    if (!key_data->Down)
8734
581k
        return false;
8735
16.2k
    if (!TestKeyOwner(key, owner_id))
8736
0
        return false;
8737
16.2k
    return true;
8738
16.2k
}
8739
8740
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
8741
325k
{
8742
325k
    return IsKeyPressed(key, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8743
325k
}
8744
8745
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
8746
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
8747
598k
{
8748
598k
    const ImGuiKeyData* key_data = GetKeyData(key);
8749
598k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8750
555k
        return false;
8751
42.8k
    const float t = key_data->DownDuration;
8752
42.8k
    if (t < 0.0f)
8753
0
        return false;
8754
42.8k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8755
8756
42.8k
    bool pressed = (t == 0.0f);
8757
42.8k
    if (!pressed && ((flags & ImGuiInputFlags_Repeat) != 0))
8758
38.4k
    {
8759
38.4k
        float repeat_delay, repeat_rate;
8760
38.4k
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
8761
38.4k
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
8762
38.4k
    }
8763
42.8k
    if (!pressed)
8764
34.0k
        return false;
8765
8.78k
    if (!TestKeyOwner(key, owner_id))
8766
0
        return false;
8767
8.78k
    return true;
8768
8.78k
}
8769
8770
bool ImGui::IsKeyReleased(ImGuiKey key)
8771
0
{
8772
0
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
8773
0
}
8774
8775
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
8776
0
{
8777
0
    const ImGuiKeyData* key_data = GetKeyData(key);
8778
0
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
8779
0
        return false;
8780
0
    if (!TestKeyOwner(key, owner_id))
8781
0
        return false;
8782
0
    return true;
8783
0
}
8784
8785
bool ImGui::IsMouseDown(ImGuiMouseButton button)
8786
0
{
8787
0
    ImGuiContext& g = *GImGui;
8788
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8789
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
8790
0
}
8791
8792
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
8793
11
{
8794
11
    ImGuiContext& g = *GImGui;
8795
11
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8796
11
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
8797
11
}
8798
8799
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
8800
5
{
8801
5
    return IsMouseClicked(button, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8802
5
}
8803
8804
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags)
8805
303
{
8806
303
    ImGuiContext& g = *GImGui;
8807
303
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8808
303
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8809
292
        return false;
8810
11
    const float t = g.IO.MouseDownDuration[button];
8811
11
    if (t < 0.0f)
8812
0
        return false;
8813
11
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8814
8815
11
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
8816
11
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
8817
11
    if (!pressed)
8818
6
        return false;
8819
8820
5
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
8821
0
        return false;
8822
8823
5
    return true;
8824
5
}
8825
8826
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
8827
0
{
8828
0
    ImGuiContext& g = *GImGui;
8829
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8830
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
8831
0
}
8832
8833
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
8834
298
{
8835
298
    ImGuiContext& g = *GImGui;
8836
298
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8837
298
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
8838
298
}
8839
8840
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
8841
2
{
8842
2
    ImGuiContext& g = *GImGui;
8843
2
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8844
2
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
8845
2
}
8846
8847
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
8848
0
{
8849
0
    ImGuiContext& g = *GImGui;
8850
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8851
0
    return g.IO.MouseClickedCount[button];
8852
0
}
8853
8854
// Test if mouse cursor is hovering given rectangle
8855
// NB- Rectangle is clipped by our current clip setting
8856
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
8857
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
8858
263k
{
8859
263k
    ImGuiContext& g = *GImGui;
8860
8861
    // Clip
8862
263k
    ImRect rect_clipped(r_min, r_max);
8863
263k
    if (clip)
8864
155k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
8865
8866
    // Expand for touch input
8867
263k
    const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
8868
263k
    if (!rect_for_touch.Contains(g.IO.MousePos))
8869
259k
        return false;
8870
4.04k
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
8871
0
        return false;
8872
4.04k
    return true;
8873
4.04k
}
8874
8875
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
8876
// [Internal] This doesn't test if the button is pressed
8877
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
8878
32
{
8879
32
    ImGuiContext& g = *GImGui;
8880
32
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8881
32
    if (lock_threshold < 0.0f)
8882
29
        lock_threshold = g.IO.MouseDragThreshold;
8883
32
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
8884
32
}
8885
8886
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
8887
34
{
8888
34
    ImGuiContext& g = *GImGui;
8889
34
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8890
34
    if (!g.IO.MouseDown[button])
8891
2
        return false;
8892
32
    return IsMouseDragPastThreshold(button, lock_threshold);
8893
34
}
8894
8895
ImVec2 ImGui::GetMousePos()
8896
6.01k
{
8897
6.01k
    ImGuiContext& g = *GImGui;
8898
6.01k
    return g.IO.MousePos;
8899
6.01k
}
8900
8901
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
8902
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
8903
0
{
8904
0
    ImGuiContext& g = *GImGui;
8905
0
    if (g.BeginPopupStack.Size > 0)
8906
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
8907
0
    return g.IO.MousePos;
8908
0
}
8909
8910
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
8911
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
8912
118k
{
8913
    // The assert is only to silence a false-positive in XCode Static Analysis.
8914
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
8915
118k
    IM_ASSERT(GImGui != NULL);
8916
118k
    const float MOUSE_INVALID = -256000.0f;
8917
118k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
8918
118k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
8919
118k
}
8920
8921
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
8922
bool ImGui::IsAnyMouseDown()
8923
0
{
8924
0
    ImGuiContext& g = *GImGui;
8925
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
8926
0
        if (g.IO.MouseDown[n])
8927
0
            return true;
8928
0
    return false;
8929
0
}
8930
8931
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
8932
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
8933
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
8934
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
8935
0
{
8936
0
    ImGuiContext& g = *GImGui;
8937
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8938
0
    if (lock_threshold < 0.0f)
8939
0
        lock_threshold = g.IO.MouseDragThreshold;
8940
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
8941
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
8942
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
8943
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
8944
0
    return ImVec2(0.0f, 0.0f);
8945
0
}
8946
8947
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
8948
0
{
8949
0
    ImGuiContext& g = *GImGui;
8950
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8951
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
8952
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
8953
0
}
8954
8955
// Get desired mouse cursor shape.
8956
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
8957
// updated during the frame, and locked in EndFrame()/Render().
8958
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
8959
ImGuiMouseCursor ImGui::GetMouseCursor()
8960
0
{
8961
0
    ImGuiContext& g = *GImGui;
8962
0
    return g.MouseCursor;
8963
0
}
8964
8965
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
8966
1
{
8967
1
    ImGuiContext& g = *GImGui;
8968
1
    g.MouseCursor = cursor_type;
8969
1
}
8970
8971
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
8972
251k
{
8973
251k
    IM_ASSERT(ImGui::IsAliasKey(key));
8974
251k
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
8975
251k
    key_data->Down = v;
8976
251k
    key_data->AnalogValue = analog_value;
8977
251k
}
8978
8979
// [Internal] Do not use directly
8980
static ImGuiKeyChord GetMergedModsFromKeys()
8981
71.8k
{
8982
71.8k
    ImGuiKeyChord mods = 0;
8983
71.8k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
8984
71.8k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
8985
71.8k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
8986
71.8k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
8987
71.8k
    return mods;
8988
71.8k
}
8989
8990
static void ImGui::UpdateKeyboardInputs()
8991
35.9k
{
8992
35.9k
    ImGuiContext& g = *GImGui;
8993
35.9k
    ImGuiIO& io = g.IO;
8994
8995
    // Import legacy keys or verify they are not used
8996
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8997
    if (io.BackendUsingLegacyKeyArrays == 0)
8998
    {
8999
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
9000
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
9001
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
9002
    }
9003
    else
9004
    {
9005
        if (g.FrameCount == 0)
9006
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9007
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
9008
9009
        // Build reverse KeyMap (Named -> Legacy)
9010
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
9011
            if (io.KeyMap[n] != -1)
9012
            {
9013
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
9014
                io.KeyMap[io.KeyMap[n]] = n;
9015
            }
9016
9017
        // Import legacy keys into new ones
9018
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9019
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
9020
            {
9021
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
9022
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
9023
                io.KeysData[key].Down = io.KeysDown[n];
9024
                if (key != n)
9025
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
9026
                io.BackendUsingLegacyKeyArrays = 1;
9027
            }
9028
        if (io.BackendUsingLegacyKeyArrays == 1)
9029
        {
9030
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
9031
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
9032
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
9033
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
9034
        }
9035
    }
9036
9037
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9038
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9039
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9040
    {
9041
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
9042
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
9043
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9044
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9045
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9046
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9047
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9048
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9049
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9050
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9051
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9052
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9053
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9054
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9055
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9056
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9057
        #undef NAV_MAP_KEY
9058
    }
9059
#endif
9060
#endif
9061
9062
    // Update aliases
9063
215k
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9064
179k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
9065
35.9k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
9066
35.9k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
9067
9068
    // Synchronize io.KeyMods and io.KeyXXX values.
9069
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9070
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9071
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9072
35.9k
    io.KeyMods = GetMergedModsFromKeys();
9073
35.9k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9074
35.9k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9075
35.9k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9076
35.9k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9077
9078
    // Clear gamepad data if disabled
9079
35.9k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9080
897k
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9081
861k
        {
9082
861k
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9083
861k
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9084
861k
        }
9085
9086
    // Update keys
9087
5.06M
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9088
5.02M
    {
9089
5.02M
        ImGuiKeyData* key_data = &io.KeysData[i];
9090
5.02M
        key_data->DownDurationPrev = key_data->DownDuration;
9091
5.02M
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9092
5.02M
    }
9093
9094
    // Update keys/input owner (named keys only): one entry per key
9095
5.06M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9096
5.02M
    {
9097
5.02M
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9098
5.02M
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9099
5.02M
        owner_data->OwnerCurr = owner_data->OwnerNext;
9100
5.02M
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
9101
4.98M
            owner_data->OwnerNext = ImGuiKeyOwner_None;
9102
5.02M
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
9103
5.02M
    }
9104
9105
35.9k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
9106
35.9k
}
9107
9108
static void ImGui::UpdateMouseInputs()
9109
35.9k
{
9110
35.9k
    ImGuiContext& g = *GImGui;
9111
35.9k
    ImGuiIO& io = g.IO;
9112
9113
    // Mouse Wheel swapping flag
9114
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9115
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9116
    // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9117
    // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9118
35.9k
    io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9119
9120
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9121
35.9k
    if (IsMousePosValid(&io.MousePos))
9122
6.01k
        io.MousePos = g.MouseLastValidPos = ImFloorSigned(io.MousePos);
9123
9124
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9125
35.9k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9126
5.29k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
9127
30.6k
    else
9128
30.6k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
9129
9130
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9131
35.9k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9132
675
        g.NavDisableMouseHover = false;
9133
9134
35.9k
    io.MousePosPrev = io.MousePos;
9135
215k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9136
179k
    {
9137
179k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9138
179k
        io.MouseClickedCount[i] = 0; // Will be filled below
9139
179k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9140
179k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9141
179k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9142
179k
        if (io.MouseClicked[i])
9143
1.23k
        {
9144
1.23k
            bool is_repeated_click = false;
9145
1.23k
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9146
507
            {
9147
507
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9148
507
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9149
465
                    is_repeated_click = true;
9150
507
            }
9151
1.23k
            if (is_repeated_click)
9152
465
                io.MouseClickedLastCount[i]++;
9153
773
            else
9154
773
                io.MouseClickedLastCount[i] = 1;
9155
1.23k
            io.MouseClickedTime[i] = g.Time;
9156
1.23k
            io.MouseClickedPos[i] = io.MousePos;
9157
1.23k
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
9158
1.23k
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
9159
1.23k
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
9160
1.23k
        }
9161
178k
        else if (io.MouseDown[i])
9162
4.32k
        {
9163
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9164
4.32k
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9165
4.32k
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
9166
4.32k
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
9167
4.32k
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
9168
4.32k
        }
9169
9170
        // We provide io.MouseDoubleClicked[] as a legacy service
9171
179k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9172
9173
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
9174
179k
        if (io.MouseClicked[i])
9175
1.23k
            g.NavDisableMouseHover = false;
9176
179k
    }
9177
35.9k
}
9178
9179
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9180
0
{
9181
0
    ImGuiContext& g = *GImGui;
9182
0
    if (window)
9183
0
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9184
0
    else
9185
0
        g.WheelingWindowReleaseTimer = 0.0f;
9186
0
    if (g.WheelingWindow == window)
9187
0
        return;
9188
0
    IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9189
0
    g.WheelingWindow = window;
9190
0
    g.WheelingWindowRefMousePos = g.IO.MousePos;
9191
0
    if (window == NULL)
9192
0
    {
9193
0
        g.WheelingWindowStartFrame = -1;
9194
0
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9195
0
    }
9196
0
}
9197
9198
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
9199
2
{
9200
    // For each axis, find window in the hierarchy that may want to use scrolling
9201
2
    ImGuiContext& g = *GImGui;
9202
2
    ImGuiWindow* windows[2] = { NULL, NULL };
9203
6
    for (int axis = 0; axis < 2; axis++)
9204
4
        if (wheel[axis] != 0.0f)
9205
3
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9206
0
            {
9207
                // Bubble up into parent window if:
9208
                // - a child window doesn't allow any scrolling.
9209
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9210
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
9211
0
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9212
0
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9213
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9214
0
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9215
0
                    break; // select this window
9216
0
            }
9217
2
    if (windows[0] == NULL && windows[1] == NULL)
9218
0
        return NULL;
9219
9220
    // If there's only one window or only one axis then there's no ambiguity
9221
2
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9222
2
        return windows[1] ? windows[1] : windows[0];
9223
9224
    // If candidate are different windows we need to decide which one to prioritize
9225
    // - First frame: only find a winner if one axis is zero.
9226
    // - Subsequent frames: only find a winner when one is more than the other.
9227
0
    if (g.WheelingWindowStartFrame == -1)
9228
0
        g.WheelingWindowStartFrame = g.FrameCount;
9229
0
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9230
0
    {
9231
0
        g.WheelingWindowWheelRemainder = wheel;
9232
0
        return NULL;
9233
0
    }
9234
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9235
0
}
9236
9237
// Called by NewFrame()
9238
void ImGui::UpdateMouseWheel()
9239
35.9k
{
9240
    // Reset the locked window if we move the mouse or after the timer elapses.
9241
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
9242
35.9k
    ImGuiContext& g = *GImGui;
9243
35.9k
    if (g.WheelingWindow != NULL)
9244
0
    {
9245
0
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9246
0
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9247
0
            g.WheelingWindowReleaseTimer = 0.0f;
9248
0
        if (g.WheelingWindowReleaseTimer <= 0.0f)
9249
0
            LockWheelingWindow(NULL, 0.0f);
9250
0
    }
9251
9252
35.9k
    ImVec2 wheel;
9253
35.9k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_None) ? g.IO.MouseWheelH : 0.0f;
9254
35.9k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_None) ? g.IO.MouseWheel : 0.0f;
9255
9256
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9257
35.9k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9258
35.9k
    if (!mouse_window || mouse_window->Collapsed)
9259
35.0k
        return;
9260
9261
    // Zoom / Scale window
9262
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9263
841
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9264
0
    {
9265
0
        LockWheelingWindow(mouse_window, wheel.y);
9266
0
        ImGuiWindow* window = mouse_window;
9267
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
9268
0
        const float scale = new_font_scale / window->FontWindowScale;
9269
0
        window->FontWindowScale = new_font_scale;
9270
0
        if (window == window->RootWindow)
9271
0
        {
9272
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9273
0
            SetWindowPos(window, window->Pos + offset, 0);
9274
0
            window->Size = ImFloor(window->Size * scale);
9275
0
            window->SizeFull = ImFloor(window->SizeFull * scale);
9276
0
        }
9277
0
        return;
9278
0
    }
9279
841
    if (g.IO.KeyCtrl)
9280
0
        return;
9281
9282
    // Mouse wheel scrolling
9283
    // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
9284
841
    if (g.IO.MouseWheelRequestAxisSwap)
9285
0
        wheel = ImVec2(wheel.y, 0.0f);
9286
9287
    // Maintain a rough average of moving magnitude on both axises
9288
    // FIXME: should by based on wall clock time rather than frame-counter
9289
841
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
9290
841
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
9291
9292
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9293
841
    wheel += g.WheelingWindowWheelRemainder;
9294
841
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9295
841
    if (wheel.x == 0.0f && wheel.y == 0.0f)
9296
839
        return;
9297
9298
    // Mouse wheel scrolling: find target and apply
9299
    // - don't renew lock if axis doesn't apply on the window.
9300
    // - select a main axis when both axises are being moved.
9301
2
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9302
2
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9303
2
        {
9304
2
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9305
2
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9306
0
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9307
2
            if (do_scroll[ImGuiAxis_X])
9308
0
            {
9309
0
                LockWheelingWindow(window, wheel.x);
9310
0
                float max_step = window->InnerRect.GetWidth() * 0.67f;
9311
0
                float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
9312
0
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
9313
0
            }
9314
2
            if (do_scroll[ImGuiAxis_Y])
9315
0
            {
9316
0
                LockWheelingWindow(window, wheel.y);
9317
0
                float max_step = window->InnerRect.GetHeight() * 0.67f;
9318
0
                float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
9319
0
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
9320
0
            }
9321
2
        }
9322
2
}
9323
9324
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9325
0
{
9326
0
    ImGuiContext& g = *GImGui;
9327
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9328
0
}
9329
9330
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9331
0
{
9332
0
    ImGuiContext& g = *GImGui;
9333
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9334
0
}
9335
9336
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9337
static const char* GetInputSourceName(ImGuiInputSource source)
9338
0
{
9339
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Clipboard" };
9340
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9341
0
    return input_source_names[source];
9342
0
}
9343
static const char* GetMouseSourceName(ImGuiMouseSource source)
9344
0
{
9345
0
    const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
9346
0
    IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
9347
0
    return mouse_source_names[source];
9348
0
}
9349
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9350
0
{
9351
0
    ImGuiContext& g = *GImGui;
9352
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
9353
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
9354
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
9355
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
9356
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
9357
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9358
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9359
0
}
9360
#endif
9361
9362
// Process input queue
9363
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9364
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9365
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
9366
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9367
35.9k
{
9368
35.9k
    ImGuiContext& g = *GImGui;
9369
35.9k
    ImGuiIO& io = g.IO;
9370
9371
    // Only trickle chars<>key when working with InputText()
9372
    // FIXME: InputText() could parse event trail?
9373
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9374
35.9k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9375
9376
35.9k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9377
35.9k
    int  mouse_button_changed = 0x00;
9378
35.9k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9379
9380
35.9k
    int event_n = 0;
9381
43.9k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
9382
9.32k
    {
9383
9.32k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9384
9.32k
        if (e->Type == ImGuiInputEventType_MousePos)
9385
1.80k
        {
9386
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9387
1.80k
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9388
1.80k
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9389
212
                break;
9390
1.59k
            io.MousePos = event_pos;
9391
1.59k
            io.MouseSource = e->MousePos.MouseSource;
9392
1.59k
            mouse_moved = true;
9393
1.59k
        }
9394
7.51k
        else if (e->Type == ImGuiInputEventType_MouseButton)
9395
2.08k
        {
9396
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9397
2.08k
            const ImGuiMouseButton button = e->MouseButton.Button;
9398
2.08k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9399
2.08k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9400
459
                break;
9401
1.62k
            if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
9402
0
                break;
9403
1.62k
            io.MouseDown[button] = e->MouseButton.Down;
9404
1.62k
            io.MouseSource = e->MouseButton.MouseSource;
9405
1.62k
            mouse_button_changed |= (1 << button);
9406
1.62k
        }
9407
5.43k
        else if (e->Type == ImGuiInputEventType_MouseWheel)
9408
892
        {
9409
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
9410
892
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9411
147
                break;
9412
745
            io.MouseWheelH += e->MouseWheel.WheelX;
9413
745
            io.MouseWheel += e->MouseWheel.WheelY;
9414
745
            io.MouseSource = e->MouseWheel.MouseSource;
9415
745
            mouse_wheeled = true;
9416
745
        }
9417
4.53k
        else if (e->Type == ImGuiInputEventType_MouseViewport)
9418
0
        {
9419
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
9420
0
        }
9421
4.53k
        else if (e->Type == ImGuiInputEventType_Key)
9422
1.61k
        {
9423
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9424
1.61k
            ImGuiKey key = e->Key.Key;
9425
1.61k
            IM_ASSERT(key != ImGuiKey_None);
9426
1.61k
            ImGuiKeyData* key_data = GetKeyData(key);
9427
1.61k
            const int key_data_index = (int)(key_data - g.IO.KeysData);
9428
1.61k
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
9429
134
                break;
9430
1.47k
            key_data->Down = e->Key.Down;
9431
1.47k
            key_data->AnalogValue = e->Key.AnalogValue;
9432
1.47k
            key_changed = true;
9433
1.47k
            key_changed_mask.SetBit(key_data_index);
9434
9435
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9436
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9437
            io.KeysDown[key_data_index] = key_data->Down;
9438
            if (io.KeyMap[key_data_index] != -1)
9439
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9440
#endif
9441
1.47k
        }
9442
2.92k
        else if (e->Type == ImGuiInputEventType_Text)
9443
2.69k
        {
9444
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9445
2.69k
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9446
352
                break;
9447
2.34k
            unsigned int c = e->Text.Char;
9448
2.34k
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9449
2.34k
            if (trickle_interleaved_keys_and_text)
9450
0
                text_inputted = true;
9451
2.34k
        }
9452
229
        else if (e->Type == ImGuiInputEventType_Focus)
9453
229
        {
9454
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
9455
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
9456
229
            const bool focus_lost = !e->AppFocused.Focused;
9457
229
            io.AppFocusLost = focus_lost;
9458
229
        }
9459
0
        else
9460
0
        {
9461
0
            IM_ASSERT(0 && "Unknown event!");
9462
0
        }
9463
9.32k
    }
9464
9465
    // Record trail (for domain-specific applications wanting to access a precise trail)
9466
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
9467
43.9k
    for (int n = 0; n < event_n; n++)
9468
8.01k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
9469
9470
    // [DEBUG]
9471
35.9k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9472
35.9k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
9473
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
9474
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
9475
35.9k
#endif
9476
9477
    // Remaining events will be processed on the next frame
9478
35.9k
    if (event_n == g.InputEventsQueue.Size)
9479
34.6k
        g.InputEventsQueue.resize(0);
9480
1.30k
    else
9481
1.30k
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
9482
9483
    // Clear buttons state when focus is lost
9484
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
9485
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
9486
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
9487
35.9k
    if (g.IO.AppFocusLost)
9488
229
        g.IO.ClearInputKeys();
9489
35.9k
}
9490
9491
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
9492
0
{
9493
0
    if (!IsNamedKeyOrModKey(key))
9494
0
        return ImGuiKeyOwner_None;
9495
9496
0
    ImGuiContext& g = *GImGui;
9497
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9498
0
    ImGuiID owner_id = owner_data->OwnerCurr;
9499
9500
0
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9501
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9502
0
            return ImGuiKeyOwner_None;
9503
9504
0
    return owner_id;
9505
0
}
9506
9507
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
9508
// TestKeyOwner(..., None) : (owner == None)
9509
// TestKeyOwner(..., Any)  : no owner test
9510
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
9511
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
9512
96.8k
{
9513
96.8k
    if (!IsNamedKeyOrModKey(key))
9514
0
        return true;
9515
9516
96.8k
    ImGuiContext& g = *GImGui;
9517
96.8k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9518
30
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9519
0
            return false;
9520
9521
96.8k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9522
96.8k
    if (owner_id == ImGuiKeyOwner_Any)
9523
13.7k
        return (owner_data->LockThisFrame == false);
9524
9525
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
9526
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
9527
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
9528
83.1k
    if (owner_data->OwnerCurr != owner_id)
9529
6
    {
9530
6
        if (owner_data->LockThisFrame)
9531
0
            return false;
9532
6
        if (owner_data->OwnerCurr != ImGuiKeyOwner_None)
9533
0
            return false;
9534
6
    }
9535
9536
83.1k
    return true;
9537
83.1k
}
9538
9539
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
9540
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
9541
// - SetKeyOwner(..., None)              : clears owner
9542
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
9543
// - SetKeyOwner(..., Any or None, Lock) : set lock
9544
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9545
5
{
9546
5
    IM_ASSERT(IsNamedKeyOrModKey(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
9547
5
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
9548
9549
5
    ImGuiContext& g = *GImGui;
9550
5
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9551
5
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
9552
9553
    // We cannot lock by default as it would likely break lots of legacy code.
9554
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
9555
5
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
9556
5
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
9557
5
}
9558
9559
// Rarely used helper
9560
void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9561
0
{
9562
0
    if (key_chord & ImGuiMod_Ctrl)      { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
9563
0
    if (key_chord & ImGuiMod_Shift)     { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
9564
0
    if (key_chord & ImGuiMod_Alt)       { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
9565
0
    if (key_chord & ImGuiMod_Super)     { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
9566
0
    if (key_chord & ImGuiMod_Shortcut)  { SetKeyOwner(ImGuiMod_Shortcut, owner_id, flags); }
9567
0
    if (key_chord & ~ImGuiMod_Mask_)    { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
9568
0
}
9569
9570
// This is more or less equivalent to:
9571
//   if (IsItemHovered() || IsItemActive())
9572
//       SetKeyOwner(key, GetItemID());
9573
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
9574
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
9575
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
9576
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
9577
0
{
9578
0
    ImGuiContext& g = *GImGui;
9579
0
    ImGuiID id = g.LastItemData.ID;
9580
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
9581
0
        return;
9582
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
9583
0
        flags |= ImGuiInputFlags_CondDefault_;
9584
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
9585
0
    {
9586
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
9587
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
9588
0
    }
9589
0
}
9590
9591
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9592
71.8k
{
9593
71.8k
    ImGuiContext& g = *GImGui;
9594
9595
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
9596
71.8k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
9597
71.8k
        flags |= ImGuiInputFlags_RouteFocused;
9598
71.8k
    if (!SetShortcutRouting(key_chord, owner_id, flags))
9599
0
        return false;
9600
9601
71.8k
    if (key_chord & ImGuiMod_Shortcut)
9602
0
        key_chord = ConvertShortcutMod(key_chord);
9603
71.8k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9604
71.8k
    if (g.IO.KeyMods != mods)
9605
71.8k
        return false;
9606
9607
    // Special storage location for mods
9608
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9609
0
    if (key == ImGuiKey_None)
9610
0
        key = ConvertSingleModFlagToKey(&g, mods);
9611
9612
0
    if (!IsKeyPressed(key, owner_id, (flags & (ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateMask_))))
9613
0
        return false;
9614
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
9615
9616
0
    return true;
9617
0
}
9618
9619
9620
//-----------------------------------------------------------------------------
9621
// [SECTION] ERROR CHECKING
9622
//-----------------------------------------------------------------------------
9623
9624
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
9625
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
9626
// If this triggers you have an issue:
9627
// - Most commonly: mismatched headers and compiled code version.
9628
// - Or: mismatched configuration #define, compilation settings, packing pragma etc.
9629
//   The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
9630
//   which is way it is required you put them in your imconfig file (and not just before including imgui.h).
9631
//   Otherwise it is possible that different compilation units would see different structure layout
9632
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
9633
1
{
9634
1
    bool error = false;
9635
1
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
9636
1
    if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
9637
1
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
9638
1
    if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
9639
1
    if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
9640
1
    if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
9641
1
    if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
9642
1
    return !error;
9643
1
}
9644
9645
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
9646
// This is causing issues and ambiguity and we need to retire that.
9647
// See https://github.com/ocornut/imgui/issues/5548 for more details.
9648
// [Scenario 1]
9649
//  Previously this would make the window content size ~200x200:
9650
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
9651
//  Instead, please submit an item:
9652
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
9653
//  Alternative:
9654
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
9655
// [Scenario 2]
9656
//  For reference this is one of the issue what we aim to fix with this change:
9657
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
9658
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
9659
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
9660
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
9661
0
{
9662
0
    ImGuiContext& g = *GImGui;
9663
0
    ImGuiWindow* window = g.CurrentWindow;
9664
0
    IM_ASSERT(window->DC.IsSetPos);
9665
0
    window->DC.IsSetPos = false;
9666
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9667
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
9668
0
        return;
9669
0
    if (window->SkipItems)
9670
0
        return;
9671
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
9672
#else
9673
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9674
#endif
9675
0
}
9676
9677
static void ImGui::ErrorCheckNewFrameSanityChecks()
9678
35.9k
{
9679
35.9k
    ImGuiContext& g = *GImGui;
9680
9681
    // Check user IM_ASSERT macro
9682
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
9683
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
9684
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
9685
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
9686
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
9687
35.9k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
9688
9689
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
9690
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
9691
#ifdef __EMSCRIPTEN__
9692
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
9693
        g.IO.DeltaTime = 0.00001f;
9694
#endif
9695
9696
    // Check user data
9697
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
9698
35.9k
    IM_ASSERT(g.Initialized);
9699
35.9k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
9700
35.9k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
9701
35.9k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
9702
35.9k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
9703
35.9k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
9704
35.9k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
9705
35.9k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
9706
35.9k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
9707
35.9k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
9708
35.9k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
9709
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9710
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
9711
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
9712
9713
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
9714
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
9715
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
9716
#endif
9717
9718
    // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
9719
35.9k
    if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
9720
1
        g.IO.ConfigWindowsResizeFromEdges = false;
9721
9722
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
9723
35.9k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
9724
35.9k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9725
35.9k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
9726
35.9k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9727
9728
    // Perform simple checks: multi-viewport and platform windows support
9729
35.9k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
9730
1
    {
9731
1
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
9732
0
        {
9733
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
9734
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
9735
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
9736
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
9737
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
9738
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
9739
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
9740
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
9741
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
9742
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
9743
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
9744
0
        }
9745
1
        else
9746
1
        {
9747
            // Disable feature, our backends do not support it
9748
1
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
9749
1
        }
9750
9751
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
9752
1
        for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
9753
0
        {
9754
0
            ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[monitor_n];
9755
0
            IM_UNUSED(mon);
9756
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
9757
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
9758
0
            IM_ASSERT(mon.DpiScale != 0.0f);
9759
0
        }
9760
1
    }
9761
35.9k
}
9762
9763
static void ImGui::ErrorCheckEndFrameSanityChecks()
9764
35.9k
{
9765
35.9k
    ImGuiContext& g = *GImGui;
9766
9767
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
9768
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
9769
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
9770
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
9771
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
9772
    // while still correctly asserting on mid-frame key press events.
9773
35.9k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
9774
35.9k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
9775
35.9k
    IM_UNUSED(key_mods);
9776
9777
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
9778
    //ErrorCheckEndFrameRecover();
9779
9780
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
9781
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
9782
35.9k
    if (g.CurrentWindowStack.Size != 1)
9783
0
    {
9784
0
        if (g.CurrentWindowStack.Size > 1)
9785
0
        {
9786
0
            ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
9787
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
9788
0
            IM_UNUSED(window);
9789
0
            while (g.CurrentWindowStack.Size > 1)
9790
0
                End();
9791
0
        }
9792
0
        else
9793
0
        {
9794
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
9795
0
        }
9796
0
    }
9797
9798
35.9k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
9799
35.9k
}
9800
9801
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
9802
// Must be called during or before EndFrame().
9803
// This is generally flawed as we are not necessarily End/Popping things in the right order.
9804
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
9805
// FIXME: Can't recover from interleaved BeginTabBar/Begin
9806
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9807
0
{
9808
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
9809
0
    ImGuiContext& g = *GImGui;
9810
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
9811
0
    {
9812
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
9813
0
        ImGuiWindow* window = g.CurrentWindow;
9814
0
        if (g.CurrentWindowStack.Size == 1)
9815
0
        {
9816
0
            IM_ASSERT(window->IsFallbackWindow);
9817
0
            break;
9818
0
        }
9819
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
9820
0
        {
9821
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
9822
0
            EndChild();
9823
0
        }
9824
0
        else
9825
0
        {
9826
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
9827
0
            End();
9828
0
        }
9829
0
    }
9830
0
}
9831
9832
// Must be called before End()/EndChild()
9833
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9834
0
{
9835
0
    ImGuiContext& g = *GImGui;
9836
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
9837
0
    {
9838
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
9839
0
        EndTable();
9840
0
    }
9841
9842
0
    ImGuiWindow* window = g.CurrentWindow;
9843
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
9844
0
    IM_ASSERT(window != NULL);
9845
0
    while (g.CurrentTabBar != NULL) //-V1044
9846
0
    {
9847
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
9848
0
        EndTabBar();
9849
0
    }
9850
0
    while (window->DC.TreeDepth > 0)
9851
0
    {
9852
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
9853
0
        TreePop();
9854
0
    }
9855
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
9856
0
    {
9857
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
9858
0
        EndGroup();
9859
0
    }
9860
0
    while (window->IDStack.Size > 1)
9861
0
    {
9862
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
9863
0
        PopID();
9864
0
    }
9865
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
9866
0
    {
9867
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
9868
0
        EndDisabled();
9869
0
    }
9870
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
9871
0
    {
9872
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
9873
0
        PopStyleColor();
9874
0
    }
9875
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
9876
0
    {
9877
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
9878
0
        PopItemFlag();
9879
0
    }
9880
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
9881
0
    {
9882
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
9883
0
        PopStyleVar();
9884
0
    }
9885
0
    while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
9886
0
    {
9887
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
9888
0
        PopFont();
9889
0
    }
9890
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
9891
0
    {
9892
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
9893
0
        PopFocusScope();
9894
0
    }
9895
0
}
9896
9897
// Save current stack sizes for later compare
9898
void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
9899
107k
{
9900
107k
    ImGuiContext& g = *ctx;
9901
107k
    ImGuiWindow* window = g.CurrentWindow;
9902
107k
    SizeOfIDStack = (short)window->IDStack.Size;
9903
107k
    SizeOfColorStack = (short)g.ColorStack.Size;
9904
107k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
9905
107k
    SizeOfFontStack = (short)g.FontStack.Size;
9906
107k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
9907
107k
    SizeOfGroupStack = (short)g.GroupStack.Size;
9908
107k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
9909
107k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
9910
107k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
9911
107k
}
9912
9913
// Compare to detect usage errors
9914
void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
9915
107k
{
9916
107k
    ImGuiContext& g = *ctx;
9917
107k
    ImGuiWindow* window = g.CurrentWindow;
9918
107k
    IM_UNUSED(window);
9919
9920
    // Window stacks
9921
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
9922
107k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
9923
9924
    // Global stacks
9925
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
9926
107k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
9927
107k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
9928
107k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
9929
107k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
9930
107k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
9931
107k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
9932
107k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
9933
107k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
9934
107k
}
9935
9936
9937
//-----------------------------------------------------------------------------
9938
// [SECTION] LAYOUT
9939
//-----------------------------------------------------------------------------
9940
// - ItemSize()
9941
// - ItemAdd()
9942
// - SameLine()
9943
// - GetCursorScreenPos()
9944
// - SetCursorScreenPos()
9945
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
9946
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
9947
// - GetCursorStartPos()
9948
// - Indent()
9949
// - Unindent()
9950
// - SetNextItemWidth()
9951
// - PushItemWidth()
9952
// - PushMultiItemsWidths()
9953
// - PopItemWidth()
9954
// - CalcItemWidth()
9955
// - CalcItemSize()
9956
// - GetTextLineHeight()
9957
// - GetTextLineHeightWithSpacing()
9958
// - GetFrameHeight()
9959
// - GetFrameHeightWithSpacing()
9960
// - GetContentRegionMax()
9961
// - GetContentRegionMaxAbs() [Internal]
9962
// - GetContentRegionAvail(),
9963
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
9964
// - BeginGroup()
9965
// - EndGroup()
9966
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
9967
//-----------------------------------------------------------------------------
9968
9969
// Advance cursor given item size for layout.
9970
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
9971
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
9972
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
9973
61.9k
{
9974
61.9k
    ImGuiContext& g = *GImGui;
9975
61.9k
    ImGuiWindow* window = g.CurrentWindow;
9976
61.9k
    if (window->SkipItems)
9977
0
        return;
9978
9979
    // We increase the height in this function to accommodate for baseline offset.
9980
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
9981
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
9982
61.9k
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
9983
9984
61.9k
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
9985
61.9k
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
9986
9987
    // Always align ourselves on pixel boundaries
9988
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
9989
61.9k
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
9990
61.9k
    window->DC.CursorPosPrevLine.y = line_y1;
9991
61.9k
    window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
9992
61.9k
    window->DC.CursorPos.y = IM_FLOOR(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
9993
61.9k
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
9994
61.9k
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
9995
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
9996
9997
61.9k
    window->DC.PrevLineSize.y = line_height;
9998
61.9k
    window->DC.CurrLineSize.y = 0.0f;
9999
61.9k
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
10000
61.9k
    window->DC.CurrLineTextBaseOffset = 0.0f;
10001
61.9k
    window->DC.IsSameLine = window->DC.IsSetPos = false;
10002
10003
    // Horizontal layout mode
10004
61.9k
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
10005
0
        SameLine();
10006
61.9k
}
10007
10008
// Declare item bounding box for clipping and interaction.
10009
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10010
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10011
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10012
209k
{
10013
209k
    ImGuiContext& g = *GImGui;
10014
209k
    ImGuiWindow* window = g.CurrentWindow;
10015
10016
    // Set item data
10017
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10018
209k
    g.LastItemData.ID = id;
10019
209k
    g.LastItemData.Rect = bb;
10020
209k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10021
209k
    g.LastItemData.InFlags = g.CurrentItemFlags | extra_flags;
10022
209k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10023
10024
    // Directional navigation processing
10025
209k
    if (id != 0)
10026
180k
    {
10027
180k
        KeepAliveID(id);
10028
10029
        // Runs prior to clipping early-out
10030
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10031
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10032
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10033
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10034
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10035
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10036
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10037
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10038
180k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10039
104k
        {
10040
104k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10041
104k
            if (g.NavId == id || g.NavAnyRequest)
10042
12.8k
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10043
3.50k
                    if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
10044
3.50k
                        NavProcessItem();
10045
104k
        }
10046
10047
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10048
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10049
        // READ THE FAQ: https://dearimgui.com/faq
10050
180k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
10051
180k
    }
10052
209k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10053
10054
#ifdef IMGUI_ENABLE_TEST_ENGINE
10055
    if (id != 0)
10056
        IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10057
#endif
10058
10059
    // Clipping test
10060
    // (FIXME: This is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
10061
    //const bool is_clipped = IsClippedEx(bb, id);
10062
    //if (is_clipped)
10063
    //    return false;
10064
209k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
10065
209k
    if (!is_rect_visible)
10066
57.5k
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId))
10067
56.8k
            if (!g.LogEnabled)
10068
56.8k
                return false;
10069
10070
    // [DEBUG]
10071
152k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10072
152k
    if (id != 0 && id == g.DebugLocateId)
10073
0
        DebugLocateItemResolveWithLastItem();
10074
152k
#endif
10075
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10076
    //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10077
    //    window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10078
10079
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10080
152k
    if (is_rect_visible)
10081
152k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10082
152k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
10083
992
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10084
152k
    return true;
10085
209k
}
10086
10087
// Gets back to previous line and continue with horizontal layout
10088
//      offset_from_start_x == 0 : follow right after previous item
10089
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
10090
//      spacing_w < 0            : use default spacing if pos_x == 0, no spacing if pos_x != 0
10091
//      spacing_w >= 0           : enforce spacing amount
10092
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
10093
0
{
10094
0
    ImGuiContext& g = *GImGui;
10095
0
    ImGuiWindow* window = g.CurrentWindow;
10096
0
    if (window->SkipItems)
10097
0
        return;
10098
10099
0
    if (offset_from_start_x != 0.0f)
10100
0
    {
10101
0
        if (spacing_w < 0.0f)
10102
0
            spacing_w = 0.0f;
10103
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
10104
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10105
0
    }
10106
0
    else
10107
0
    {
10108
0
        if (spacing_w < 0.0f)
10109
0
            spacing_w = g.Style.ItemSpacing.x;
10110
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
10111
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10112
0
    }
10113
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
10114
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
10115
0
    window->DC.IsSameLine = true;
10116
0
}
10117
10118
ImVec2 ImGui::GetCursorScreenPos()
10119
41.9k
{
10120
41.9k
    ImGuiWindow* window = GetCurrentWindowRead();
10121
41.9k
    return window->DC.CursorPos;
10122
41.9k
}
10123
10124
// 2022/08/05: Setting cursor position also extend boundaries (via modifying CursorMaxPos) used to compute window size, group size etc.
10125
// I believe this was is a judicious choice but it's probably being relied upon (it has been the case since 1.31 and 1.50)
10126
// It would be sane if we requested user to use SetCursorPos() + Dummy(ImVec2(0,0)) to extend CursorMaxPos...
10127
void ImGui::SetCursorScreenPos(const ImVec2& pos)
10128
0
{
10129
0
    ImGuiWindow* window = GetCurrentWindow();
10130
0
    window->DC.CursorPos = pos;
10131
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10132
0
    window->DC.IsSetPos = true;
10133
0
}
10134
10135
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
10136
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
10137
ImVec2 ImGui::GetCursorPos()
10138
0
{
10139
0
    ImGuiWindow* window = GetCurrentWindowRead();
10140
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
10141
0
}
10142
10143
float ImGui::GetCursorPosX()
10144
0
{
10145
0
    ImGuiWindow* window = GetCurrentWindowRead();
10146
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
10147
0
}
10148
10149
float ImGui::GetCursorPosY()
10150
0
{
10151
0
    ImGuiWindow* window = GetCurrentWindowRead();
10152
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
10153
0
}
10154
10155
void ImGui::SetCursorPos(const ImVec2& local_pos)
10156
0
{
10157
0
    ImGuiWindow* window = GetCurrentWindow();
10158
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
10159
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10160
0
    window->DC.IsSetPos = true;
10161
0
}
10162
10163
void ImGui::SetCursorPosX(float x)
10164
0
{
10165
0
    ImGuiWindow* window = GetCurrentWindow();
10166
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
10167
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
10168
0
    window->DC.IsSetPos = true;
10169
0
}
10170
10171
void ImGui::SetCursorPosY(float y)
10172
0
{
10173
0
    ImGuiWindow* window = GetCurrentWindow();
10174
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
10175
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
10176
0
    window->DC.IsSetPos = true;
10177
0
}
10178
10179
ImVec2 ImGui::GetCursorStartPos()
10180
0
{
10181
0
    ImGuiWindow* window = GetCurrentWindowRead();
10182
0
    return window->DC.CursorStartPos - window->Pos;
10183
0
}
10184
10185
void ImGui::Indent(float indent_w)
10186
0
{
10187
0
    ImGuiContext& g = *GImGui;
10188
0
    ImGuiWindow* window = GetCurrentWindow();
10189
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10190
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10191
0
}
10192
10193
void ImGui::Unindent(float indent_w)
10194
0
{
10195
0
    ImGuiContext& g = *GImGui;
10196
0
    ImGuiWindow* window = GetCurrentWindow();
10197
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10198
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10199
0
}
10200
10201
// Affect large frame+labels widgets only.
10202
void ImGui::SetNextItemWidth(float item_width)
10203
0
{
10204
0
    ImGuiContext& g = *GImGui;
10205
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
10206
0
    g.NextItemData.Width = item_width;
10207
0
}
10208
10209
// FIXME: Remove the == 0.0f behavior?
10210
void ImGui::PushItemWidth(float item_width)
10211
0
{
10212
0
    ImGuiContext& g = *GImGui;
10213
0
    ImGuiWindow* window = g.CurrentWindow;
10214
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10215
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
10216
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10217
0
}
10218
10219
void ImGui::PushMultiItemsWidths(int components, float w_full)
10220
0
{
10221
0
    ImGuiContext& g = *GImGui;
10222
0
    ImGuiWindow* window = g.CurrentWindow;
10223
0
    const ImGuiStyle& style = g.Style;
10224
0
    const float w_item_one  = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
10225
0
    const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
10226
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10227
0
    window->DC.ItemWidthStack.push_back(w_item_last);
10228
0
    for (int i = 0; i < components - 2; i++)
10229
0
        window->DC.ItemWidthStack.push_back(w_item_one);
10230
0
    window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
10231
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10232
0
}
10233
10234
void ImGui::PopItemWidth()
10235
0
{
10236
0
    ImGuiWindow* window = GetCurrentWindow();
10237
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
10238
0
    window->DC.ItemWidthStack.pop_back();
10239
0
}
10240
10241
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
10242
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
10243
float ImGui::CalcItemWidth()
10244
0
{
10245
0
    ImGuiContext& g = *GImGui;
10246
0
    ImGuiWindow* window = g.CurrentWindow;
10247
0
    float w;
10248
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
10249
0
        w = g.NextItemData.Width;
10250
0
    else
10251
0
        w = window->DC.ItemWidth;
10252
0
    if (w < 0.0f)
10253
0
    {
10254
0
        float region_max_x = GetContentRegionMaxAbs().x;
10255
0
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
10256
0
    }
10257
0
    w = IM_FLOOR(w);
10258
0
    return w;
10259
0
}
10260
10261
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
10262
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
10263
// Note that only CalcItemWidth() is publicly exposed.
10264
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
10265
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
10266
0
{
10267
0
    ImGuiContext& g = *GImGui;
10268
0
    ImGuiWindow* window = g.CurrentWindow;
10269
10270
0
    ImVec2 region_max;
10271
0
    if (size.x < 0.0f || size.y < 0.0f)
10272
0
        region_max = GetContentRegionMaxAbs();
10273
10274
0
    if (size.x == 0.0f)
10275
0
        size.x = default_w;
10276
0
    else if (size.x < 0.0f)
10277
0
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
10278
10279
0
    if (size.y == 0.0f)
10280
0
        size.y = default_h;
10281
0
    else if (size.y < 0.0f)
10282
0
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
10283
10284
0
    return size;
10285
0
}
10286
10287
float ImGui::GetTextLineHeight()
10288
0
{
10289
0
    ImGuiContext& g = *GImGui;
10290
0
    return g.FontSize;
10291
0
}
10292
10293
float ImGui::GetTextLineHeightWithSpacing()
10294
35.9k
{
10295
35.9k
    ImGuiContext& g = *GImGui;
10296
35.9k
    return g.FontSize + g.Style.ItemSpacing.y;
10297
35.9k
}
10298
10299
float ImGui::GetFrameHeight()
10300
18
{
10301
18
    ImGuiContext& g = *GImGui;
10302
18
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
10303
18
}
10304
10305
float ImGui::GetFrameHeightWithSpacing()
10306
0
{
10307
0
    ImGuiContext& g = *GImGui;
10308
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
10309
0
}
10310
10311
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
10312
10313
// FIXME: This is in window space (not screen space!).
10314
ImVec2 ImGui::GetContentRegionMax()
10315
0
{
10316
0
    ImGuiContext& g = *GImGui;
10317
0
    ImGuiWindow* window = g.CurrentWindow;
10318
0
    ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
10319
0
    if (window->DC.CurrentColumns || g.CurrentTable)
10320
0
        mx.x = window->WorkRect.Max.x - window->Pos.x;
10321
0
    return mx;
10322
0
}
10323
10324
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
10325
ImVec2 ImGui::GetContentRegionMaxAbs()
10326
35.9k
{
10327
35.9k
    ImGuiContext& g = *GImGui;
10328
35.9k
    ImGuiWindow* window = g.CurrentWindow;
10329
35.9k
    ImVec2 mx = window->ContentRegionRect.Max;
10330
35.9k
    if (window->DC.CurrentColumns || g.CurrentTable)
10331
0
        mx.x = window->WorkRect.Max.x;
10332
35.9k
    return mx;
10333
35.9k
}
10334
10335
ImVec2 ImGui::GetContentRegionAvail()
10336
35.9k
{
10337
35.9k
    ImGuiWindow* window = GImGui->CurrentWindow;
10338
35.9k
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
10339
35.9k
}
10340
10341
// In window space (not screen space!)
10342
ImVec2 ImGui::GetWindowContentRegionMin()
10343
0
{
10344
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10345
0
    return window->ContentRegionRect.Min - window->Pos;
10346
0
}
10347
10348
ImVec2 ImGui::GetWindowContentRegionMax()
10349
35.9k
{
10350
35.9k
    ImGuiWindow* window = GImGui->CurrentWindow;
10351
35.9k
    return window->ContentRegionRect.Max - window->Pos;
10352
35.9k
}
10353
10354
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
10355
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
10356
// FIXME-OPT: Could we safely early out on ->SkipItems?
10357
void ImGui::BeginGroup()
10358
0
{
10359
0
    ImGuiContext& g = *GImGui;
10360
0
    ImGuiWindow* window = g.CurrentWindow;
10361
10362
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
10363
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10364
0
    group_data.WindowID = window->ID;
10365
0
    group_data.BackupCursorPos = window->DC.CursorPos;
10366
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
10367
0
    group_data.BackupIndent = window->DC.Indent;
10368
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
10369
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
10370
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
10371
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
10372
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
10373
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
10374
0
    group_data.EmitItem = true;
10375
10376
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
10377
0
    window->DC.Indent = window->DC.GroupOffset;
10378
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
10379
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
10380
0
    if (g.LogEnabled)
10381
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10382
0
}
10383
10384
void ImGui::EndGroup()
10385
0
{
10386
0
    ImGuiContext& g = *GImGui;
10387
0
    ImGuiWindow* window = g.CurrentWindow;
10388
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
10389
10390
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10391
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
10392
10393
0
    if (window->DC.IsSetPos)
10394
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
10395
10396
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
10397
10398
0
    window->DC.CursorPos = group_data.BackupCursorPos;
10399
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
10400
0
    window->DC.Indent = group_data.BackupIndent;
10401
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
10402
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
10403
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
10404
0
    if (g.LogEnabled)
10405
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10406
10407
0
    if (!group_data.EmitItem)
10408
0
    {
10409
0
        g.GroupStack.pop_back();
10410
0
        return;
10411
0
    }
10412
10413
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
10414
0
    ItemSize(group_bb.GetSize());
10415
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
10416
10417
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
10418
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
10419
    // Also if you grep for LastItemId you'll notice it is only used in that context.
10420
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
10421
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
10422
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
10423
0
    if (group_contains_curr_active_id)
10424
0
        g.LastItemData.ID = g.ActiveId;
10425
0
    else if (group_contains_prev_active_id)
10426
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
10427
0
    g.LastItemData.Rect = group_bb;
10428
10429
    // Forward Hovered flag
10430
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
10431
0
    if (group_contains_curr_hovered_id)
10432
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
10433
10434
    // Forward Edited flag
10435
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
10436
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
10437
10438
    // Forward Deactivated flag
10439
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
10440
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
10441
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
10442
10443
0
    g.GroupStack.pop_back();
10444
    //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
10445
0
}
10446
10447
10448
//-----------------------------------------------------------------------------
10449
// [SECTION] SCROLLING
10450
//-----------------------------------------------------------------------------
10451
10452
// Helper to snap on edges when aiming at an item very close to the edge,
10453
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
10454
// When we refactor the scrolling API this may be configurable with a flag?
10455
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
10456
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
10457
0
{
10458
0
    if (target <= snap_min + snap_threshold)
10459
0
        return ImLerp(snap_min, target, center_ratio);
10460
0
    if (target >= snap_max - snap_threshold)
10461
0
        return ImLerp(target, snap_max, center_ratio);
10462
0
    return target;
10463
0
}
10464
10465
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
10466
108k
{
10467
108k
    ImVec2 scroll = window->Scroll;
10468
108k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
10469
324k
    for (int axis = 0; axis < 2; axis++)
10470
216k
    {
10471
216k
        if (window->ScrollTarget[axis] < FLT_MAX)
10472
23.6k
        {
10473
23.6k
            float center_ratio = window->ScrollTargetCenterRatio[axis];
10474
23.6k
            float scroll_target = window->ScrollTarget[axis];
10475
23.6k
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
10476
0
            {
10477
0
                float snap_min = 0.0f;
10478
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
10479
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
10480
0
            }
10481
23.6k
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
10482
23.6k
        }
10483
216k
        scroll[axis] = IM_FLOOR(ImMax(scroll[axis], 0.0f));
10484
216k
        if (!window->Collapsed && !window->SkipItems)
10485
196k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
10486
216k
    }
10487
108k
    return scroll;
10488
108k
}
10489
10490
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
10491
0
{
10492
0
    ImGuiContext& g = *GImGui;
10493
0
    ImGuiWindow* window = g.CurrentWindow;
10494
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
10495
0
}
10496
10497
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10498
0
{
10499
0
    ScrollToRectEx(window, item_rect, flags);
10500
0
}
10501
10502
// Scroll to keep newly navigated item fully into view
10503
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10504
544
{
10505
544
    ImGuiContext& g = *GImGui;
10506
544
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
10507
544
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
10508
544
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
10509
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
10510
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
10511
10512
    // Check that only one behavior is selected per axis
10513
544
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
10514
544
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
10515
10516
    // Defaults
10517
544
    ImGuiScrollFlags in_flags = flags;
10518
544
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
10519
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
10520
544
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
10521
430
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
10522
10523
544
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
10524
544
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
10525
544
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10526
544
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10527
10528
544
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
10529
0
    {
10530
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
10531
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
10532
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
10533
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
10534
0
    }
10535
544
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
10536
0
    {
10537
0
        if (can_be_fully_visible_x)
10538
0
            SetScrollFromPosX(window, ImFloor((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
10539
0
        else
10540
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
10541
0
    }
10542
10543
544
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
10544
60
    {
10545
60
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
10546
60
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
10547
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
10548
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
10549
60
    }
10550
484
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
10551
0
    {
10552
0
        if (can_be_fully_visible_y)
10553
0
            SetScrollFromPosY(window, ImFloor((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
10554
0
        else
10555
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
10556
0
    }
10557
10558
544
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
10559
544
    ImVec2 delta_scroll = next_scroll - window->Scroll;
10560
10561
    // Also scroll parent window to keep us into view if necessary
10562
544
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
10563
0
    {
10564
        // FIXME-SCROLL: May be an option?
10565
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
10566
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
10567
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
10568
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
10569
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
10570
0
    }
10571
10572
544
    return delta_scroll;
10573
544
}
10574
10575
float ImGui::GetScrollX()
10576
53.9k
{
10577
53.9k
    ImGuiWindow* window = GImGui->CurrentWindow;
10578
53.9k
    return window->Scroll.x;
10579
53.9k
}
10580
10581
float ImGui::GetScrollY()
10582
53.9k
{
10583
53.9k
    ImGuiWindow* window = GImGui->CurrentWindow;
10584
53.9k
    return window->Scroll.y;
10585
53.9k
}
10586
10587
float ImGui::GetScrollMaxX()
10588
0
{
10589
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10590
0
    return window->ScrollMax.x;
10591
0
}
10592
10593
float ImGui::GetScrollMaxY()
10594
0
{
10595
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10596
0
    return window->ScrollMax.y;
10597
0
}
10598
10599
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
10600
8.41k
{
10601
8.41k
    window->ScrollTarget.x = scroll_x;
10602
8.41k
    window->ScrollTargetCenterRatio.x = 0.0f;
10603
8.41k
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10604
8.41k
}
10605
10606
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
10607
15.4k
{
10608
15.4k
    window->ScrollTarget.y = scroll_y;
10609
15.4k
    window->ScrollTargetCenterRatio.y = 0.0f;
10610
15.4k
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10611
15.4k
}
10612
10613
void ImGui::SetScrollX(float scroll_x)
10614
7.94k
{
10615
7.94k
    ImGuiContext& g = *GImGui;
10616
7.94k
    SetScrollX(g.CurrentWindow, scroll_x);
10617
7.94k
}
10618
10619
void ImGui::SetScrollY(float scroll_y)
10620
13.7k
{
10621
13.7k
    ImGuiContext& g = *GImGui;
10622
13.7k
    SetScrollY(g.CurrentWindow, scroll_y);
10623
13.7k
}
10624
10625
// Note that a local position will vary depending on initial scroll value,
10626
// This is a little bit confusing so bear with us:
10627
//  - local_pos = (absolution_pos - window->Pos)
10628
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
10629
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
10630
//  - They mostly exist because of legacy API.
10631
// Following the rules above, when trying to work with scrolling code, consider that:
10632
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
10633
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
10634
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
10635
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
10636
0
{
10637
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
10638
0
    window->ScrollTarget.x = IM_FLOOR(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
10639
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
10640
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10641
0
}
10642
10643
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
10644
60
{
10645
60
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
10646
60
    window->ScrollTarget.y = IM_FLOOR(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
10647
60
    window->ScrollTargetCenterRatio.y = center_y_ratio;
10648
60
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10649
60
}
10650
10651
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
10652
0
{
10653
0
    ImGuiContext& g = *GImGui;
10654
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
10655
0
}
10656
10657
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
10658
0
{
10659
0
    ImGuiContext& g = *GImGui;
10660
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
10661
0
}
10662
10663
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
10664
void ImGui::SetScrollHereX(float center_x_ratio)
10665
0
{
10666
0
    ImGuiContext& g = *GImGui;
10667
0
    ImGuiWindow* window = g.CurrentWindow;
10668
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
10669
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
10670
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
10671
10672
    // Tweak: snap on edges when aiming at an item very close to the edge
10673
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
10674
0
}
10675
10676
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
10677
void ImGui::SetScrollHereY(float center_y_ratio)
10678
0
{
10679
0
    ImGuiContext& g = *GImGui;
10680
0
    ImGuiWindow* window = g.CurrentWindow;
10681
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
10682
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
10683
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
10684
10685
    // Tweak: snap on edges when aiming at an item very close to the edge
10686
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
10687
0
}
10688
10689
//-----------------------------------------------------------------------------
10690
// [SECTION] TOOLTIPS
10691
//-----------------------------------------------------------------------------
10692
10693
bool ImGui::BeginTooltip()
10694
0
{
10695
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
10696
0
}
10697
10698
bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
10699
0
{
10700
0
    ImGuiContext& g = *GImGui;
10701
10702
0
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
10703
0
    {
10704
        // The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
10705
        // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
10706
        // Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
10707
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
10708
0
        ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
10709
0
        SetNextWindowPos(tooltip_pos);
10710
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
10711
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
10712
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
10713
0
    }
10714
10715
0
    char window_name[16];
10716
0
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
10717
0
    if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
10718
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
10719
0
            if (window->Active)
10720
0
            {
10721
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
10722
0
                SetWindowHiddendAndSkipItemsForCurrentFrame(window);
10723
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
10724
0
            }
10725
0
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
10726
0
    Begin(window_name, NULL, flags | extra_window_flags);
10727
    // 2023-03-09: Added bool return value to the API, but currently always returning true.
10728
    // If this ever returns false we need to update BeginDragDropSource() accordingly.
10729
    //if (!ret)
10730
    //    End();
10731
    //return ret;
10732
0
    return true;
10733
0
}
10734
10735
void ImGui::EndTooltip()
10736
0
{
10737
0
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
10738
0
    End();
10739
0
}
10740
10741
void ImGui::SetTooltipV(const char* fmt, va_list args)
10742
0
{
10743
0
    if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePreviousTooltip, ImGuiWindowFlags_None))
10744
0
        return;
10745
0
    TextV(fmt, args);
10746
0
    EndTooltip();
10747
0
}
10748
10749
void ImGui::SetTooltip(const char* fmt, ...)
10750
0
{
10751
0
    va_list args;
10752
0
    va_start(args, fmt);
10753
0
    SetTooltipV(fmt, args);
10754
0
    va_end(args);
10755
0
}
10756
10757
//-----------------------------------------------------------------------------
10758
// [SECTION] POPUPS
10759
//-----------------------------------------------------------------------------
10760
10761
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
10762
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
10763
0
{
10764
0
    ImGuiContext& g = *GImGui;
10765
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
10766
0
    {
10767
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
10768
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
10769
0
        IM_ASSERT(id == 0);
10770
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10771
0
            return g.OpenPopupStack.Size > 0;
10772
0
        else
10773
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
10774
0
    }
10775
0
    else
10776
0
    {
10777
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10778
0
        {
10779
            // Return true if the popup is open anywhere in the popup stack
10780
0
            for (int n = 0; n < g.OpenPopupStack.Size; n++)
10781
0
                if (g.OpenPopupStack[n].PopupId == id)
10782
0
                    return true;
10783
0
            return false;
10784
0
        }
10785
0
        else
10786
0
        {
10787
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
10788
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
10789
0
        }
10790
0
    }
10791
0
}
10792
10793
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
10794
0
{
10795
0
    ImGuiContext& g = *GImGui;
10796
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
10797
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
10798
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
10799
0
    return IsPopupOpen(id, popup_flags);
10800
0
}
10801
10802
// Also see FindBlockingModal(NULL)
10803
ImGuiWindow* ImGui::GetTopMostPopupModal()
10804
107k
{
10805
107k
    ImGuiContext& g = *GImGui;
10806
107k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
10807
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
10808
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
10809
0
                return popup;
10810
107k
    return NULL;
10811
107k
}
10812
10813
// See Demo->Stacked Modal to confirm what this is for.
10814
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
10815
35.9k
{
10816
35.9k
    ImGuiContext& g = *GImGui;
10817
35.9k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
10818
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
10819
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
10820
0
                return popup;
10821
35.9k
    return NULL;
10822
35.9k
}
10823
10824
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
10825
0
{
10826
0
    ImGuiContext& g = *GImGui;
10827
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
10828
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
10829
0
    OpenPopupEx(id, popup_flags);
10830
0
}
10831
10832
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
10833
0
{
10834
0
    OpenPopupEx(id, popup_flags);
10835
0
}
10836
10837
// Mark popup as open (toggle toward open state).
10838
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
10839
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
10840
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
10841
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
10842
0
{
10843
0
    ImGuiContext& g = *GImGui;
10844
0
    ImGuiWindow* parent_window = g.CurrentWindow;
10845
0
    const int current_stack_size = g.BeginPopupStack.Size;
10846
10847
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
10848
0
        if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
10849
0
            return;
10850
10851
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
10852
0
    popup_ref.PopupId = id;
10853
0
    popup_ref.Window = NULL;
10854
0
    popup_ref.BackupNavWindow = g.NavWindow;            // When popup closes focus may be restored to NavWindow (depend on window type).
10855
0
    popup_ref.OpenFrameCount = g.FrameCount;
10856
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
10857
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
10858
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
10859
10860
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
10861
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
10862
0
    {
10863
0
        g.OpenPopupStack.push_back(popup_ref);
10864
0
    }
10865
0
    else
10866
0
    {
10867
        // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
10868
        // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
10869
        // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
10870
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
10871
0
        {
10872
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
10873
0
        }
10874
0
        else
10875
0
        {
10876
            // Close child popups if any, then flag popup for open/reopen
10877
0
            ClosePopupToLevel(current_stack_size, false);
10878
0
            g.OpenPopupStack.push_back(popup_ref);
10879
0
        }
10880
10881
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
10882
        // This is equivalent to what ClosePopupToLevel() does.
10883
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
10884
        //    FocusWindow(parent_window);
10885
0
    }
10886
0
}
10887
10888
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
10889
// This function closes any popups that are over 'ref_window'.
10890
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
10891
9.50k
{
10892
9.50k
    ImGuiContext& g = *GImGui;
10893
9.50k
    if (g.OpenPopupStack.Size == 0)
10894
9.50k
        return;
10895
10896
    // Don't close our own child popup windows.
10897
0
    int popup_count_to_keep = 0;
10898
0
    if (ref_window)
10899
0
    {
10900
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
10901
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
10902
0
        {
10903
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
10904
0
            if (!popup.Window)
10905
0
                continue;
10906
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
10907
0
            if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
10908
0
                continue;
10909
10910
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
10911
            // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
10912
            //     Window -> Popup1 -> Popup2 -> Popup3
10913
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
10914
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
10915
0
            bool ref_window_is_descendent_of_popup = false;
10916
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
10917
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
10918
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
10919
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
10920
0
                    {
10921
0
                        ref_window_is_descendent_of_popup = true;
10922
0
                        break;
10923
0
                    }
10924
0
            if (!ref_window_is_descendent_of_popup)
10925
0
                break;
10926
0
        }
10927
0
    }
10928
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
10929
0
    {
10930
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
10931
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
10932
0
    }
10933
0
}
10934
10935
void ImGui::ClosePopupsExceptModals()
10936
0
{
10937
0
    ImGuiContext& g = *GImGui;
10938
10939
0
    int popup_count_to_keep;
10940
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
10941
0
    {
10942
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
10943
0
        if (!window || (window->Flags & ImGuiWindowFlags_Modal))
10944
0
            break;
10945
0
    }
10946
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
10947
0
        ClosePopupToLevel(popup_count_to_keep, true);
10948
0
}
10949
10950
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
10951
0
{
10952
0
    ImGuiContext& g = *GImGui;
10953
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
10954
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
10955
10956
    // Trim open popup stack
10957
0
    ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
10958
0
    ImGuiWindow* popup_backup_nav_window = g.OpenPopupStack[remaining].BackupNavWindow;
10959
0
    g.OpenPopupStack.resize(remaining);
10960
10961
0
    if (restore_focus_to_window_under_popup)
10962
0
    {
10963
0
        ImGuiWindow* focus_window = (popup_window && popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : popup_backup_nav_window;
10964
0
        if (focus_window && !focus_window->WasActive && popup_window)
10965
0
            FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
10966
0
        else
10967
0
            FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
10968
0
    }
10969
0
}
10970
10971
// Close the popup we have begin-ed into.
10972
void ImGui::CloseCurrentPopup()
10973
0
{
10974
0
    ImGuiContext& g = *GImGui;
10975
0
    int popup_idx = g.BeginPopupStack.Size - 1;
10976
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
10977
0
        return;
10978
10979
    // Closing a menu closes its top-most parent popup (unless a modal)
10980
0
    while (popup_idx > 0)
10981
0
    {
10982
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
10983
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
10984
0
        bool close_parent = false;
10985
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
10986
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
10987
0
                close_parent = true;
10988
0
        if (!close_parent)
10989
0
            break;
10990
0
        popup_idx--;
10991
0
    }
10992
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
10993
0
    ClosePopupToLevel(popup_idx, true);
10994
10995
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
10996
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
10997
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
10998
0
    if (ImGuiWindow* window = g.NavWindow)
10999
0
        window->DC.NavHideHighlightOneFrame = true;
11000
0
}
11001
11002
// Attention! BeginPopup() adds default flags which BeginPopupEx()!
11003
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
11004
0
{
11005
0
    ImGuiContext& g = *GImGui;
11006
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11007
0
    {
11008
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11009
0
        return false;
11010
0
    }
11011
11012
0
    char name[20];
11013
0
    if (flags & ImGuiWindowFlags_ChildMenu)
11014
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuCount); // Recycle windows based on depth
11015
0
    else
11016
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
11017
11018
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
11019
0
    bool is_open = Begin(name, NULL, flags);
11020
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
11021
0
        EndPopup();
11022
11023
0
    return is_open;
11024
0
}
11025
11026
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
11027
0
{
11028
0
    ImGuiContext& g = *GImGui;
11029
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
11030
0
    {
11031
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11032
0
        return false;
11033
0
    }
11034
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
11035
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11036
0
    return BeginPopupEx(id, flags);
11037
0
}
11038
11039
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
11040
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
11041
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
11042
0
{
11043
0
    ImGuiContext& g = *GImGui;
11044
0
    ImGuiWindow* window = g.CurrentWindow;
11045
0
    const ImGuiID id = window->GetID(name);
11046
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11047
0
    {
11048
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11049
0
        return false;
11050
0
    }
11051
11052
    // Center modal windows by default for increased visibility
11053
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
11054
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
11055
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
11056
0
    {
11057
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
11058
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
11059
0
    }
11060
11061
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
11062
0
    const bool is_open = Begin(name, p_open, flags);
11063
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
11064
0
    {
11065
0
        EndPopup();
11066
0
        if (is_open)
11067
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
11068
0
        return false;
11069
0
    }
11070
0
    return is_open;
11071
0
}
11072
11073
void ImGui::EndPopup()
11074
0
{
11075
0
    ImGuiContext& g = *GImGui;
11076
0
    ImGuiWindow* window = g.CurrentWindow;
11077
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
11078
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
11079
11080
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
11081
0
    if (g.NavWindow == window)
11082
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
11083
11084
    // Child-popups don't need to be laid out
11085
0
    IM_ASSERT(g.WithinEndChild == false);
11086
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
11087
0
        g.WithinEndChild = true;
11088
0
    End();
11089
0
    g.WithinEndChild = false;
11090
0
}
11091
11092
// Helper to open a popup if mouse button is released over the item
11093
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
11094
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
11095
0
{
11096
0
    ImGuiContext& g = *GImGui;
11097
0
    ImGuiWindow* window = g.CurrentWindow;
11098
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11099
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11100
0
    {
11101
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11102
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11103
0
        OpenPopupEx(id, popup_flags);
11104
0
    }
11105
0
}
11106
11107
// This is a helper to handle the simplest case of associating one named popup to one given widget.
11108
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
11109
// - To create a popup with a specific identifier, pass it in str_id.
11110
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
11111
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
11112
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
11113
//   This is essentially the same as:
11114
//       id = str_id ? GetID(str_id) : GetItemID();
11115
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
11116
//       return BeginPopup(id);
11117
//   Which is essentially the same as:
11118
//       id = str_id ? GetID(str_id) : GetItemID();
11119
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
11120
//           OpenPopup(id);
11121
//       return BeginPopup(id);
11122
//   The main difference being that this is tweaked to avoid computing the ID twice.
11123
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
11124
0
{
11125
0
    ImGuiContext& g = *GImGui;
11126
0
    ImGuiWindow* window = g.CurrentWindow;
11127
0
    if (window->SkipItems)
11128
0
        return false;
11129
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11130
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11131
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11132
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11133
0
        OpenPopupEx(id, popup_flags);
11134
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11135
0
}
11136
11137
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
11138
0
{
11139
0
    ImGuiContext& g = *GImGui;
11140
0
    ImGuiWindow* window = g.CurrentWindow;
11141
0
    if (!str_id)
11142
0
        str_id = "window_context";
11143
0
    ImGuiID id = window->GetID(str_id);
11144
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11145
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11146
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
11147
0
            OpenPopupEx(id, popup_flags);
11148
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11149
0
}
11150
11151
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
11152
0
{
11153
0
    ImGuiContext& g = *GImGui;
11154
0
    ImGuiWindow* window = g.CurrentWindow;
11155
0
    if (!str_id)
11156
0
        str_id = "void_context";
11157
0
    ImGuiID id = window->GetID(str_id);
11158
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11159
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
11160
0
        if (GetTopMostPopupModal() == NULL)
11161
0
            OpenPopupEx(id, popup_flags);
11162
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11163
0
}
11164
11165
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
11166
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
11167
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
11168
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
11169
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
11170
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
11171
0
{
11172
0
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
11173
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
11174
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
11175
11176
    // Combo Box policy (we want a connecting edge)
11177
0
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
11178
0
    {
11179
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
11180
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11181
0
        {
11182
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11183
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11184
0
                continue;
11185
0
            ImVec2 pos;
11186
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
11187
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
11188
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
11189
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
11190
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
11191
0
                continue;
11192
0
            *last_dir = dir;
11193
0
            return pos;
11194
0
        }
11195
0
    }
11196
11197
    // Tooltip and Default popup policy
11198
    // (Always first try the direction we used on the last frame, if any)
11199
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
11200
0
    {
11201
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
11202
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11203
0
        {
11204
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11205
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11206
0
                continue;
11207
11208
0
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
11209
0
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
11210
11211
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
11212
0
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
11213
0
                continue;
11214
0
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
11215
0
                continue;
11216
11217
0
            ImVec2 pos;
11218
0
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
11219
0
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
11220
11221
            // Clamp top-left corner of popup
11222
0
            pos.x = ImMax(pos.x, r_outer.Min.x);
11223
0
            pos.y = ImMax(pos.y, r_outer.Min.y);
11224
11225
0
            *last_dir = dir;
11226
0
            return pos;
11227
0
        }
11228
0
    }
11229
11230
    // Fallback when not enough room:
11231
0
    *last_dir = ImGuiDir_None;
11232
11233
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
11234
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
11235
0
        return ref_pos + ImVec2(2, 2);
11236
11237
    // Otherwise try to keep within display
11238
0
    ImVec2 pos = ref_pos;
11239
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
11240
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
11241
0
    return pos;
11242
0
}
11243
11244
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
11245
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
11246
0
{
11247
0
    ImGuiContext& g = *GImGui;
11248
0
    ImRect r_screen;
11249
0
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
11250
0
    {
11251
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
11252
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
11253
0
        r_screen.Min = monitor.WorkPos;
11254
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
11255
0
    }
11256
0
    else
11257
0
    {
11258
        // Use the full viewport area (not work area) for popups
11259
0
        r_screen = window->Viewport->GetMainRect();
11260
0
    }
11261
0
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
11262
0
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
11263
0
    return r_screen;
11264
0
}
11265
11266
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
11267
0
{
11268
0
    ImGuiContext& g = *GImGui;
11269
11270
0
    ImRect r_outer = GetPopupAllowedExtentRect(window);
11271
0
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
11272
0
    {
11273
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
11274
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
11275
0
        ImGuiWindow* parent_window = window->ParentWindow;
11276
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
11277
0
        ImRect r_avoid;
11278
0
        if (parent_window->DC.MenuBarAppending)
11279
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
11280
0
        else
11281
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
11282
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
11283
0
    }
11284
0
    if (window->Flags & ImGuiWindowFlags_Popup)
11285
0
    {
11286
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
11287
0
    }
11288
0
    if (window->Flags & ImGuiWindowFlags_Tooltip)
11289
0
    {
11290
        // Position tooltip (always follows mouse)
11291
0
        float sc = g.Style.MouseCursorScale;
11292
0
        ImVec2 ref_pos = NavCalcPreferredRefPos();
11293
0
        ImRect r_avoid;
11294
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
11295
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
11296
0
        else
11297
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
11298
0
        return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
11299
0
    }
11300
0
    IM_ASSERT(0);
11301
0
    return window->Pos;
11302
0
}
11303
11304
//-----------------------------------------------------------------------------
11305
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
11306
//-----------------------------------------------------------------------------
11307
11308
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
11309
// In our terminology those should be interchangeable, yet right now this is super confusing.
11310
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
11311
11312
void ImGui::SetNavWindow(ImGuiWindow* window)
11313
9.31k
{
11314
9.31k
    ImGuiContext& g = *GImGui;
11315
9.31k
    if (g.NavWindow != window)
11316
9.31k
    {
11317
9.31k
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
11318
9.31k
        g.NavWindow = window;
11319
9.31k
    }
11320
9.31k
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11321
9.31k
    NavUpdateAnyRequestFlag();
11322
9.31k
}
11323
11324
void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
11325
4.71k
{
11326
4.71k
    ImGuiContext& g = *GImGui;
11327
4.71k
    g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
11328
4.71k
}
11329
11330
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
11331
758
{
11332
758
    ImGuiContext& g = *GImGui;
11333
758
    IM_ASSERT(g.NavWindow != NULL);
11334
758
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
11335
758
    g.NavId = id;
11336
758
    g.NavLayer = nav_layer;
11337
758
    g.NavFocusScopeId = focus_scope_id;
11338
758
    g.NavWindow->NavLastIds[nav_layer] = id;
11339
758
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
11340
11341
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11342
758
    NavClearPreferredPosForAxis(ImGuiAxis_X);
11343
758
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
11344
758
}
11345
11346
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
11347
5
{
11348
5
    ImGuiContext& g = *GImGui;
11349
5
    IM_ASSERT(id != 0);
11350
11351
5
    if (g.NavWindow != window)
11352
5
       SetNavWindow(window);
11353
11354
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
11355
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
11356
5
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
11357
5
    g.NavId = id;
11358
5
    g.NavLayer = nav_layer;
11359
5
    g.NavFocusScopeId = g.CurrentFocusScopeId;
11360
5
    window->NavLastIds[nav_layer] = id;
11361
5
    if (g.LastItemData.ID == id)
11362
5
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11363
11364
5
    if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
11365
0
        g.NavDisableMouseHover = true;
11366
5
    else
11367
5
        g.NavDisableHighlight = true;
11368
11369
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11370
5
    NavClearPreferredPosForAxis(ImGuiAxis_X);
11371
5
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
11372
5
}
11373
11374
static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
11375
693
{
11376
693
    if (ImFabs(dx) > ImFabs(dy))
11377
15
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
11378
678
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
11379
693
}
11380
11381
static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
11382
1.38k
{
11383
1.38k
    if (cand_max < curr_min)
11384
353
        return cand_max - curr_min;
11385
1.03k
    if (curr_max < cand_min)
11386
325
        return cand_min - curr_max;
11387
708
    return 0.0f;
11388
1.03k
}
11389
11390
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
11391
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
11392
2.07k
{
11393
2.07k
    ImGuiContext& g = *GImGui;
11394
2.07k
    ImGuiWindow* window = g.CurrentWindow;
11395
2.07k
    if (g.NavLayer != window->DC.NavLayerCurrent)
11396
1.38k
        return false;
11397
11398
    // FIXME: Those are not good variables names
11399
693
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
11400
693
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
11401
693
    g.NavScoringDebugCount++;
11402
11403
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
11404
693
    if (window->ParentWindow == g.NavWindow)
11405
0
    {
11406
0
        IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
11407
0
        if (!window->ClipRect.Overlaps(cand))
11408
0
            return false;
11409
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
11410
0
    }
11411
11412
    // Compute distance between boxes
11413
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
11414
693
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
11415
693
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
11416
693
    if (dby != 0.0f && dbx != 0.0f)
11417
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
11418
693
    float dist_box = ImFabs(dbx) + ImFabs(dby);
11419
11420
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
11421
693
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
11422
693
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
11423
693
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
11424
11425
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
11426
693
    ImGuiDir quadrant;
11427
693
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
11428
693
    if (dbx != 0.0f || dby != 0.0f)
11429
678
    {
11430
        // For non-overlapping boxes, use distance between boxes
11431
678
        dax = dbx;
11432
678
        day = dby;
11433
678
        dist_axial = dist_box;
11434
678
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
11435
678
    }
11436
15
    else if (dcx != 0.0f || dcy != 0.0f)
11437
15
    {
11438
        // For overlapping boxes with different centers, use distance between centers
11439
15
        dax = dcx;
11440
15
        day = dcy;
11441
15
        dist_axial = dist_center;
11442
15
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
11443
15
    }
11444
0
    else
11445
0
    {
11446
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
11447
0
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
11448
0
    }
11449
11450
693
    const ImGuiDir move_dir = g.NavMoveDir;
11451
#if IMGUI_DEBUG_NAV_SCORING
11452
    char buf[200];
11453
    if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
11454
    {
11455
        if (quadrant == move_dir)
11456
        {
11457
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
11458
            ImDrawList* draw_list = GetForegroundDrawList(window);
11459
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
11460
            draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
11461
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
11462
        }
11463
    }
11464
    const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
11465
    const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
11466
    if (debug_hovering || debug_tty)
11467
    {
11468
        ImFormatString(buf, IM_ARRAYSIZE(buf),
11469
            "d-box    (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial  (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c",
11470
            dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
11471
        if (debug_hovering)
11472
        {
11473
            ImDrawList* draw_list = GetForegroundDrawList(window);
11474
            draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
11475
            draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
11476
            draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
11477
            draw_list->AddText(cand.Max, ~0U, buf);
11478
        }
11479
        if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
11480
    }
11481
#endif
11482
11483
    // Is it in the quadrant we're interested in moving to?
11484
693
    bool new_best = false;
11485
693
    if (quadrant == move_dir)
11486
678
    {
11487
        // Does it beat the current best candidate?
11488
678
        if (dist_box < result->DistBox)
11489
678
        {
11490
678
            result->DistBox = dist_box;
11491
678
            result->DistCenter = dist_center;
11492
678
            return true;
11493
678
        }
11494
0
        if (dist_box == result->DistBox)
11495
0
        {
11496
            // Try using distance between center points to break ties
11497
0
            if (dist_center < result->DistCenter)
11498
0
            {
11499
0
                result->DistCenter = dist_center;
11500
0
                new_best = true;
11501
0
            }
11502
0
            else if (dist_center == result->DistCenter)
11503
0
            {
11504
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
11505
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
11506
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
11507
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
11508
0
                    new_best = true;
11509
0
            }
11510
0
        }
11511
0
    }
11512
11513
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
11514
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
11515
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
11516
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
11517
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
11518
15
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
11519
15
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
11520
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
11521
0
            {
11522
0
                result->DistAxial = dist_axial;
11523
0
                new_best = true;
11524
0
            }
11525
11526
15
    return new_best;
11527
693
}
11528
11529
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
11530
813
{
11531
813
    ImGuiContext& g = *GImGui;
11532
813
    ImGuiWindow* window = g.CurrentWindow;
11533
813
    result->Window = window;
11534
813
    result->ID = g.LastItemData.ID;
11535
813
    result->FocusScopeId = g.CurrentFocusScopeId;
11536
813
    result->InFlags = g.LastItemData.InFlags;
11537
813
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11538
813
}
11539
11540
// True when current work location may be scrolled horizontally when moving left / right.
11541
// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
11542
void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
11543
179k
{
11544
179k
    ImGuiContext& g = *GImGui;
11545
179k
    ImGuiWindow* window = g.CurrentWindow;
11546
179k
    window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
11547
179k
}
11548
11549
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
11550
// This is called after LastItemData is set.
11551
static void ImGui::NavProcessItem()
11552
3.50k
{
11553
3.50k
    ImGuiContext& g = *GImGui;
11554
3.50k
    ImGuiWindow* window = g.CurrentWindow;
11555
3.50k
    const ImGuiID id = g.LastItemData.ID;
11556
3.50k
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
11557
11558
    // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
11559
3.50k
    if (window->DC.NavIsScrollPushableX == false)
11560
0
    {
11561
0
        g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
11562
0
        g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
11563
0
    }
11564
3.50k
    const ImRect nav_bb = g.LastItemData.NavRect;
11565
11566
    // Process Init Request
11567
3.50k
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
11568
16
    {
11569
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
11570
16
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
11571
16
        if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
11572
16
        {
11573
16
            NavApplyItemToResult(&g.NavInitResult);
11574
16
        }
11575
16
        if (candidate_for_nav_default_focus)
11576
16
        {
11577
16
            g.NavInitRequest = false; // Found a match, clear request
11578
16
            NavUpdateAnyRequestFlag();
11579
16
        }
11580
16
    }
11581
11582
    // Process Move Request (scoring for navigation)
11583
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
11584
3.50k
    if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
11585
1.81k
    {
11586
1.81k
        const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) != 0;
11587
1.81k
        if (is_tabbing)
11588
299
        {
11589
299
            NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
11590
299
        }
11591
1.51k
        else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
11592
1.39k
        {
11593
1.39k
            ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
11594
1.39k
            if (NavScoreItem(result))
11595
460
                NavApplyItemToResult(result);
11596
11597
            // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
11598
1.39k
            const float VISIBLE_RATIO = 0.70f;
11599
1.39k
            if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
11600
700
                if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
11601
681
                    if (NavScoreItem(&g.NavMoveResultLocalVisible))
11602
218
                        NavApplyItemToResult(&g.NavMoveResultLocalVisible);
11603
1.39k
        }
11604
1.81k
    }
11605
11606
    // Update information for currently focused/navigated item
11607
3.50k
    if (g.NavId == id)
11608
2.39k
    {
11609
2.39k
        if (g.NavWindow != window)
11610
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
11611
2.39k
        g.NavLayer = window->DC.NavLayerCurrent;
11612
2.39k
        g.NavFocusScopeId = g.CurrentFocusScopeId;
11613
2.39k
        g.NavIdIsAlive = true;
11614
2.39k
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
11615
2.39k
    }
11616
3.50k
}
11617
11618
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
11619
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
11620
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
11621
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
11622
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
11623
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
11624
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
11625
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
11626
299
{
11627
299
    ImGuiContext& g = *GImGui;
11628
11629
299
    if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
11630
299
        if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
11631
180
            return;
11632
11633
    // - Can always land on an item when using API call.
11634
    // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
11635
    // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
11636
119
    bool can_stop;
11637
119
    if (move_flags & ImGuiNavMoveFlags_FocusApi)
11638
0
        can_stop = true;
11639
119
    else
11640
119
        can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
11641
11642
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
11643
119
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
11644
119
    if (g.NavTabbingDir == +1)
11645
119
    {
11646
        // Tab Forward or SetKeyboardFocusHere() with >= 0
11647
119
        if (can_stop && g.NavTabbingResultFirst.ID == 0)
11648
119
            NavApplyItemToResult(&g.NavTabbingResultFirst);
11649
119
        if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
11650
0
            NavMoveRequestResolveWithLastItem(result);
11651
119
        else if (g.NavId == id)
11652
119
            g.NavTabbingCounter = 1;
11653
119
    }
11654
0
    else if (g.NavTabbingDir == -1)
11655
0
    {
11656
        // Tab Backward
11657
0
        if (g.NavId == id)
11658
0
        {
11659
0
            if (result->ID)
11660
0
            {
11661
0
                g.NavMoveScoringItems = false;
11662
0
                NavUpdateAnyRequestFlag();
11663
0
            }
11664
0
        }
11665
0
        else if (can_stop)
11666
0
        {
11667
            // Keep applying until reaching NavId
11668
0
            NavApplyItemToResult(result);
11669
0
        }
11670
0
    }
11671
0
    else if (g.NavTabbingDir == 0)
11672
0
    {
11673
0
        if (can_stop && g.NavId == id)
11674
0
            NavMoveRequestResolveWithLastItem(result);
11675
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
11676
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
11677
0
    }
11678
119
}
11679
11680
bool ImGui::NavMoveRequestButNoResultYet()
11681
32.7k
{
11682
32.7k
    ImGuiContext& g = *GImGui;
11683
32.7k
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
11684
32.7k
}
11685
11686
// FIXME: ScoringRect is not set
11687
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11688
3.94k
{
11689
3.94k
    ImGuiContext& g = *GImGui;
11690
3.94k
    IM_ASSERT(g.NavWindow != NULL);
11691
11692
3.94k
    if (move_flags & ImGuiNavMoveFlags_Tabbing)
11693
1.74k
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
11694
11695
3.94k
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
11696
3.94k
    g.NavMoveDir = move_dir;
11697
3.94k
    g.NavMoveDirForDebug = move_dir;
11698
3.94k
    g.NavMoveClipDir = clip_dir;
11699
3.94k
    g.NavMoveFlags = move_flags;
11700
3.94k
    g.NavMoveScrollFlags = scroll_flags;
11701
3.94k
    g.NavMoveForwardToNextFrame = false;
11702
3.94k
    g.NavMoveKeyMods = g.IO.KeyMods;
11703
3.94k
    g.NavMoveResultLocal.Clear();
11704
3.94k
    g.NavMoveResultLocalVisible.Clear();
11705
3.94k
    g.NavMoveResultOther.Clear();
11706
3.94k
    g.NavTabbingCounter = 0;
11707
3.94k
    g.NavTabbingResultFirst.Clear();
11708
3.94k
    NavUpdateAnyRequestFlag();
11709
3.94k
}
11710
11711
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
11712
0
{
11713
0
    ImGuiContext& g = *GImGui;
11714
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
11715
0
    NavApplyItemToResult(result);
11716
0
    NavUpdateAnyRequestFlag();
11717
0
}
11718
11719
void ImGui::NavMoveRequestCancel()
11720
21
{
11721
21
    ImGuiContext& g = *GImGui;
11722
21
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11723
21
    NavUpdateAnyRequestFlag();
11724
21
}
11725
11726
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
11727
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11728
0
{
11729
0
    ImGuiContext& g = *GImGui;
11730
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
11731
0
    NavMoveRequestCancel();
11732
0
    g.NavMoveForwardToNextFrame = true;
11733
0
    g.NavMoveDir = move_dir;
11734
0
    g.NavMoveClipDir = clip_dir;
11735
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
11736
0
    g.NavMoveScrollFlags = scroll_flags;
11737
0
}
11738
11739
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
11740
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
11741
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
11742
0
{
11743
0
    ImGuiContext& g = *GImGui;
11744
0
    IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
11745
11746
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
11747
    // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
11748
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
11749
0
        g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
11750
0
}
11751
11752
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
11753
// This way we could find the last focused window among our children. It would be much less confusing this way?
11754
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
11755
28.2k
{
11756
28.2k
    ImGuiWindow* parent = nav_window;
11757
53.6k
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
11758
25.4k
        parent = parent->ParentWindow;
11759
28.2k
    if (parent && parent != nav_window)
11760
25.4k
        parent->NavLastChildNavWindow = nav_window;
11761
28.2k
}
11762
11763
// Restore the last focused child.
11764
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
11765
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
11766
0
{
11767
0
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
11768
0
        return window->NavLastChildNavWindow;
11769
0
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
11770
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
11771
0
            return tab->Window;
11772
0
    return window;
11773
0
}
11774
11775
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
11776
0
{
11777
0
    ImGuiContext& g = *GImGui;
11778
0
    if (layer == ImGuiNavLayer_Main)
11779
0
    {
11780
0
        ImGuiWindow* prev_nav_window = g.NavWindow;
11781
0
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
11782
0
        if (prev_nav_window)
11783
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
11784
0
    }
11785
0
    ImGuiWindow* window = g.NavWindow;
11786
0
    if (window->NavLastIds[layer] != 0)
11787
0
    {
11788
0
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
11789
0
    }
11790
0
    else
11791
0
    {
11792
0
        g.NavLayer = layer;
11793
0
        NavInitWindow(window, true);
11794
0
    }
11795
0
}
11796
11797
void ImGui::NavRestoreHighlightAfterMove()
11798
1.18k
{
11799
1.18k
    ImGuiContext& g = *GImGui;
11800
1.18k
    g.NavDisableHighlight = false;
11801
1.18k
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
11802
1.18k
}
11803
11804
static inline void ImGui::NavUpdateAnyRequestFlag()
11805
49.2k
{
11806
49.2k
    ImGuiContext& g = *GImGui;
11807
49.2k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
11808
49.2k
    if (g.NavAnyRequest)
11809
49.2k
        IM_ASSERT(g.NavWindow != NULL);
11810
49.2k
}
11811
11812
// This needs to be called before we submit any widget (aka in or before Begin)
11813
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
11814
6
{
11815
    // FIXME: ChildWindow test here is wrong for docking
11816
6
    ImGuiContext& g = *GImGui;
11817
6
    IM_ASSERT(window == g.NavWindow);
11818
11819
6
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
11820
0
    {
11821
0
        g.NavId = 0;
11822
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
11823
0
        return;
11824
0
    }
11825
11826
6
    bool init_for_nav = false;
11827
6
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
11828
6
        init_for_nav = true;
11829
6
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
11830
6
    if (init_for_nav)
11831
6
    {
11832
6
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
11833
6
        g.NavInitRequest = true;
11834
6
        g.NavInitRequestFromMove = false;
11835
6
        g.NavInitResult.ID = 0;
11836
6
        NavUpdateAnyRequestFlag();
11837
6
    }
11838
0
    else
11839
0
    {
11840
0
        g.NavId = window->NavLastIds[0];
11841
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
11842
0
    }
11843
6
}
11844
11845
static ImVec2 ImGui::NavCalcPreferredRefPos()
11846
0
{
11847
0
    ImGuiContext& g = *GImGui;
11848
0
    ImGuiWindow* window = g.NavWindow;
11849
0
    if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
11850
0
    {
11851
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
11852
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
11853
        // In theory we could move that +1.0f offset in OpenPopupEx()
11854
0
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
11855
0
        return ImVec2(p.x + 1.0f, p.y);
11856
0
    }
11857
0
    else
11858
0
    {
11859
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
11860
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
11861
0
        ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
11862
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
11863
0
        {
11864
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11865
0
            rect_rel.Translate(window->Scroll - next_scroll);
11866
0
        }
11867
0
        ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
11868
0
        ImGuiViewport* viewport = window->Viewport;
11869
0
        return ImFloor(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
11870
0
    }
11871
0
}
11872
11873
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
11874
0
{
11875
0
    ImGuiContext& g = *GImGui;
11876
0
    float repeat_delay, repeat_rate;
11877
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
11878
11879
0
    ImGuiKey key_less, key_more;
11880
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
11881
0
    {
11882
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
11883
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
11884
0
    }
11885
0
    else
11886
0
    {
11887
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
11888
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
11889
0
    }
11890
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
11891
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
11892
0
        amount = 0.0f;
11893
0
    return amount;
11894
0
}
11895
11896
static void ImGui::NavUpdate()
11897
35.9k
{
11898
35.9k
    ImGuiContext& g = *GImGui;
11899
35.9k
    ImGuiIO& io = g.IO;
11900
11901
35.9k
    io.WantSetMousePos = false;
11902
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
11903
11904
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
11905
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
11906
35.9k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
11907
35.9k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
11908
35.9k
    if (nav_gamepad_active)
11909
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
11910
0
            if (IsKeyDown(key))
11911
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
11912
35.9k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
11913
35.9k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
11914
35.9k
    if (nav_keyboard_active)
11915
35.9k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
11916
251k
            if (IsKeyDown(key))
11917
9.43k
                g.NavInputSource = ImGuiInputSource_Keyboard;
11918
11919
    // Process navigation init request (select first/default focus)
11920
35.9k
    g.NavJustMovedToId = 0;
11921
35.9k
    if (g.NavInitResult.ID != 0)
11922
16
        NavInitRequestApplyResult();
11923
35.9k
    g.NavInitRequest = false;
11924
35.9k
    g.NavInitRequestFromMove = false;
11925
35.9k
    g.NavInitResult.ID = 0;
11926
11927
    // Process navigation move request
11928
35.9k
    if (g.NavMoveSubmitted)
11929
3.73k
        NavMoveRequestApplyResult();
11930
35.9k
    g.NavTabbingCounter = 0;
11931
35.9k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11932
11933
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
11934
35.9k
    bool set_mouse_pos = false;
11935
35.9k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
11936
794
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
11937
793
            set_mouse_pos = true;
11938
35.9k
    g.NavMousePosDirty = false;
11939
35.9k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
11940
11941
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
11942
35.9k
    if (g.NavWindow)
11943
28.2k
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
11944
35.9k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
11945
170
        g.NavWindow->NavLastChildNavWindow = NULL;
11946
11947
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
11948
35.9k
    NavUpdateWindowing();
11949
11950
    // Set output flags for user application
11951
35.9k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
11952
35.9k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
11953
11954
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
11955
35.9k
    NavUpdateCancelRequest();
11956
11957
    // Process manual activation request
11958
35.9k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
11959
35.9k
    g.NavActivateFlags = ImGuiActivateFlags_None;
11960
35.9k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
11961
2.92k
    {
11962
2.92k
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate));
11963
2.92k
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, false)));
11964
2.92k
        const bool input_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Enter)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput));
11965
2.92k
        const bool input_pressed = input_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Enter, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, false)));
11966
2.92k
        if (g.ActiveId == 0 && activate_pressed)
11967
3
        {
11968
3
            g.NavActivateId = g.NavId;
11969
3
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
11970
3
        }
11971
2.92k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
11972
1
        {
11973
1
            g.NavActivateId = g.NavId;
11974
1
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
11975
1
        }
11976
2.92k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
11977
148
            g.NavActivateDownId = g.NavId;
11978
2.92k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
11979
4
            g.NavActivatePressedId = g.NavId;
11980
2.92k
    }
11981
35.9k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
11982
0
        g.NavDisableHighlight = true;
11983
35.9k
    if (g.NavActivateId != 0)
11984
35.9k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
11985
11986
    // Process programmatic activation request
11987
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
11988
35.9k
    if (g.NavNextActivateId != 0)
11989
0
    {
11990
0
        g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
11991
0
        g.NavActivateFlags = g.NavNextActivateFlags;
11992
0
    }
11993
35.9k
    g.NavNextActivateId = 0;
11994
11995
    // Process move requests
11996
35.9k
    NavUpdateCreateMoveRequest();
11997
35.9k
    if (g.NavMoveDir == ImGuiDir_None)
11998
33.7k
        NavUpdateCreateTabbingRequest();
11999
35.9k
    NavUpdateAnyRequestFlag();
12000
35.9k
    g.NavIdIsAlive = false;
12001
12002
    // Scrolling
12003
35.9k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
12004
28.2k
    {
12005
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
12006
28.2k
        ImGuiWindow* window = g.NavWindow;
12007
28.2k
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
12008
28.2k
        const ImGuiDir move_dir = g.NavMoveDir;
12009
28.2k
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
12010
1.14k
        {
12011
1.14k
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
12012
469
                SetScrollX(window, ImFloor(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
12013
1.14k
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
12014
676
                SetScrollY(window, ImFloor(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
12015
1.14k
        }
12016
12017
        // *Normal* Manual scroll with LStick
12018
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
12019
28.2k
        if (nav_gamepad_active)
12020
0
        {
12021
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12022
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
12023
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
12024
0
                SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
12025
0
            if (scroll_dir.y != 0.0f)
12026
0
                SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
12027
0
        }
12028
28.2k
    }
12029
12030
    // Always prioritize mouse highlight if navigation is disabled
12031
35.9k
    if (!nav_keyboard_active && !nav_gamepad_active)
12032
0
    {
12033
0
        g.NavDisableHighlight = true;
12034
0
        g.NavDisableMouseHover = set_mouse_pos = false;
12035
0
    }
12036
12037
    // Update mouse position if requested
12038
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
12039
35.9k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
12040
0
    {
12041
0
        io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos();
12042
0
        io.WantSetMousePos = true;
12043
        //IMGUI_DEBUG_LOG_IO("SetMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
12044
0
    }
12045
12046
    // [DEBUG]
12047
35.9k
    g.NavScoringDebugCount = 0;
12048
#if IMGUI_DEBUG_NAV_RECTS
12049
    if (ImGuiWindow* debug_window = g.NavWindow)
12050
    {
12051
        ImDrawList* draw_list = GetForegroundDrawList(debug_window);
12052
        int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); }
12053
        //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
12054
    }
12055
#endif
12056
35.9k
}
12057
12058
void ImGui::NavInitRequestApplyResult()
12059
16
{
12060
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
12061
16
    ImGuiContext& g = *GImGui;
12062
16
    if (!g.NavWindow)
12063
2
        return;
12064
12065
14
    ImGuiNavItemData* result = &g.NavInitResult;
12066
14
    if (g.NavId != result->ID)
12067
14
    {
12068
14
        g.NavJustMovedToId = result->ID;
12069
14
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12070
14
        g.NavJustMovedToKeyMods = 0;
12071
14
    }
12072
12073
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
12074
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
12075
14
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12076
14
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12077
14
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
12078
14
    if (g.NavInitRequestFromMove)
12079
14
        NavRestoreHighlightAfterMove();
12080
14
}
12081
12082
// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
12083
static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
12084
2.19k
{
12085
    // Bias initial rect
12086
2.19k
    ImGuiContext& g = *GImGui;
12087
2.19k
    const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
12088
12089
    // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
12090
    // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
12091
    // - But each successful move sets new bias on one axis, only cleared when using mouse.
12092
2.19k
    if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
12093
2.19k
    {
12094
2.19k
        if (preferred_pos_rel.x == FLT_MAX)
12095
874
            preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
12096
2.19k
        if (preferred_pos_rel.y == FLT_MAX)
12097
1.38k
            preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
12098
2.19k
    }
12099
12100
    // Apply general bias on the other axis
12101
2.19k
    if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
12102
1.72k
        r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
12103
471
    else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
12104
471
        r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
12105
2.19k
}
12106
12107
void ImGui::NavUpdateCreateMoveRequest()
12108
35.9k
{
12109
35.9k
    ImGuiContext& g = *GImGui;
12110
35.9k
    ImGuiIO& io = g.IO;
12111
35.9k
    ImGuiWindow* window = g.NavWindow;
12112
35.9k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12113
35.9k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12114
12115
35.9k
    if (g.NavMoveForwardToNextFrame && window != NULL)
12116
0
    {
12117
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
12118
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
12119
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
12120
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
12121
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
12122
0
    }
12123
35.9k
    else
12124
35.9k
    {
12125
        // Initiate directional inputs request
12126
35.9k
        g.NavMoveDir = ImGuiDir_None;
12127
35.9k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
12128
35.9k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
12129
35.9k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
12130
28.2k
        {
12131
28.2k
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
12132
28.2k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
12133
28.2k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
12134
28.2k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
12135
28.2k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
12136
28.2k
        }
12137
35.9k
        g.NavMoveClipDir = g.NavMoveDir;
12138
35.9k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
12139
35.9k
    }
12140
12141
    // Update PageUp/PageDown/Home/End scroll
12142
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
12143
35.9k
    float scoring_rect_offset_y = 0.0f;
12144
35.9k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
12145
26.7k
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
12146
35.9k
    if (scoring_rect_offset_y != 0.0f)
12147
592
    {
12148
592
        g.NavScoringNoClipRect = window->InnerRect;
12149
592
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
12150
592
    }
12151
12152
    // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
12153
#if IMGUI_DEBUG_NAV_SCORING
12154
    //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
12155
    //    g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
12156
    if (io.KeyCtrl)
12157
    {
12158
        if (g.NavMoveDir == ImGuiDir_None)
12159
            g.NavMoveDir = g.NavMoveDirForDebug;
12160
        g.NavMoveClipDir = g.NavMoveDir;
12161
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
12162
    }
12163
#endif
12164
12165
    // Submit
12166
35.9k
    g.NavMoveForwardToNextFrame = false;
12167
35.9k
    if (g.NavMoveDir != ImGuiDir_None)
12168
2.19k
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
12169
12170
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
12171
35.9k
    if (g.NavMoveSubmitted && g.NavId == 0)
12172
1.29k
    {
12173
1.29k
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
12174
1.29k
        g.NavInitRequest = g.NavInitRequestFromMove = true;
12175
1.29k
        g.NavInitResult.ID = 0;
12176
1.29k
        g.NavDisableHighlight = false;
12177
1.29k
    }
12178
12179
    // When using gamepad, we project the reference nav bounding box into window visible area.
12180
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
12181
    // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
12182
35.9k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
12183
0
    {
12184
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
12185
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
12186
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
12187
12188
        // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
12189
        // Otherwise 'inner_rect_rel' would be off on the move result frame.
12190
0
        inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
12191
12192
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
12193
0
        {
12194
0
            IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
12195
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
12196
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
12197
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
12198
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
12199
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
12200
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
12201
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
12202
0
            g.NavId = 0;
12203
0
        }
12204
0
    }
12205
12206
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
12207
35.9k
    ImRect scoring_rect;
12208
35.9k
    if (window != NULL)
12209
28.2k
    {
12210
28.2k
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
12211
28.2k
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
12212
28.2k
        scoring_rect.TranslateY(scoring_rect_offset_y);
12213
28.2k
        if (g.NavMoveSubmitted)
12214
2.19k
            NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
12215
28.2k
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
12216
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
12217
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
12218
28.2k
    }
12219
35.9k
    g.NavScoringRect = scoring_rect;
12220
35.9k
    g.NavScoringNoClipRect.Add(scoring_rect);
12221
35.9k
}
12222
12223
void ImGui::NavUpdateCreateTabbingRequest()
12224
33.7k
{
12225
33.7k
    ImGuiContext& g = *GImGui;
12226
33.7k
    ImGuiWindow* window = g.NavWindow;
12227
33.7k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
12228
33.7k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
12229
7.66k
        return;
12230
12231
26.0k
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
12232
26.0k
    if (!tab_pressed)
12233
24.3k
        return;
12234
12235
    // Initiate tabbing request
12236
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
12237
    // Initially this was designed to use counters and modulo arithmetic, but that could not work with unsubmitted items (list clipper). Instead we use a strategy close to other move requests.
12238
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
12239
1.74k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12240
1.74k
    if (nav_keyboard_active)
12241
1.74k
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
12242
0
    else
12243
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
12244
1.74k
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_Tabbing | ImGuiNavMoveFlags_Activate;
12245
1.74k
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
12246
1.74k
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
12247
1.74k
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
12248
1.74k
    g.NavTabbingCounter = -1;
12249
1.74k
}
12250
12251
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
12252
void ImGui::NavMoveRequestApplyResult()
12253
3.73k
{
12254
3.73k
    ImGuiContext& g = *GImGui;
12255
#if IMGUI_DEBUG_NAV_SCORING
12256
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
12257
        return;
12258
#endif
12259
12260
    // Select which result to use
12261
3.73k
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
12262
12263
    // Tabbing forward wrap
12264
3.73k
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && result == NULL)
12265
1.65k
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
12266
114
            result = &g.NavTabbingResultFirst;
12267
12268
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
12269
3.73k
    const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12270
3.73k
    if (result == NULL)
12271
3.18k
    {
12272
3.18k
        if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
12273
1.54k
            g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
12274
3.18k
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12275
431
            NavRestoreHighlightAfterMove();
12276
3.18k
        NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
12277
3.18k
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
12278
3.18k
        return;
12279
3.18k
    }
12280
12281
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
12282
544
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
12283
335
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
12284
0
            result = &g.NavMoveResultLocalVisible;
12285
12286
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
12287
544
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
12288
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
12289
0
            result = &g.NavMoveResultOther;
12290
544
    IM_ASSERT(g.NavWindow && result->Window);
12291
12292
    // Scroll to keep newly navigated item fully into view.
12293
544
    if (g.NavLayer == ImGuiNavLayer_Main)
12294
544
    {
12295
544
        ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
12296
544
        ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
12297
12298
544
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
12299
95
        {
12300
            // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
12301
95
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
12302
95
            SetScrollY(result->Window, scroll_target);
12303
95
        }
12304
544
    }
12305
12306
544
    if (g.NavWindow != result->Window)
12307
0
    {
12308
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
12309
0
        g.NavWindow = result->Window;
12310
0
    }
12311
544
    if (g.ActiveId != result->ID)
12312
544
        ClearActiveID();
12313
544
    if (g.NavId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
12314
0
    {
12315
        // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
12316
0
        g.NavJustMovedToId = result->ID;
12317
0
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12318
0
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
12319
0
    }
12320
12321
    // Apply new NavID/Focus
12322
544
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12323
544
    ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
12324
544
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12325
12326
    // Restore last preferred position for current axis
12327
    // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
12328
544
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) == 0)
12329
430
    {
12330
430
        preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
12331
430
        g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
12332
430
    }
12333
12334
    // Tabbing: Activates Inputable, otherwise only Focus
12335
544
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
12336
114
        g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
12337
12338
    // Activate
12339
544
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
12340
0
    {
12341
0
        g.NavNextActivateId = result->ID;
12342
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
12343
0
        g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
12344
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
12345
0
            g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState;
12346
0
    }
12347
12348
    // Enable nav highlight
12349
544
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12350
544
        NavRestoreHighlightAfterMove();
12351
544
}
12352
12353
// Process NavCancel input (to close a popup, get back to parent, clear focus)
12354
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
12355
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
12356
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
12357
static void ImGui::NavUpdateCancelRequest()
12358
35.9k
{
12359
35.9k
    ImGuiContext& g = *GImGui;
12360
35.9k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12361
35.9k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12362
35.9k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, ImGuiKeyOwner_None)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, ImGuiKeyOwner_None)))
12363
35.6k
        return;
12364
12365
239
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
12366
239
    if (g.ActiveId != 0)
12367
0
    {
12368
0
        ClearActiveID();
12369
0
    }
12370
239
    else if (g.NavLayer != ImGuiNavLayer_Main)
12371
0
    {
12372
        // Leave the "menu" layer
12373
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12374
0
        NavRestoreHighlightAfterMove();
12375
0
    }
12376
239
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
12377
194
    {
12378
        // Exit child window
12379
194
        ImGuiWindow* child_window = g.NavWindow;
12380
194
        ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
12381
194
        IM_ASSERT(child_window->ChildId != 0);
12382
194
        ImRect child_rect = child_window->Rect();
12383
194
        FocusWindow(parent_window);
12384
194
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_rect));
12385
194
        NavRestoreHighlightAfterMove();
12386
194
    }
12387
45
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
12388
0
    {
12389
        // Close open popup/menu
12390
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
12391
0
    }
12392
45
    else
12393
45
    {
12394
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
12395
45
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
12396
19
            g.NavWindow->NavLastIds[0] = 0;
12397
45
        g.NavId = 0;
12398
45
    }
12399
239
}
12400
12401
// Handle PageUp/PageDown/Home/End keys
12402
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
12403
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
12404
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
12405
static float ImGui::NavUpdatePageUpPageDown()
12406
26.7k
{
12407
26.7k
    ImGuiContext& g = *GImGui;
12408
26.7k
    ImGuiWindow* window = g.NavWindow;
12409
26.7k
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
12410
0
        return 0.0f;
12411
12412
26.7k
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_None);
12413
26.7k
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_None);
12414
26.7k
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12415
26.7k
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12416
26.7k
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
12417
19.9k
        return 0.0f;
12418
12419
6.85k
    if (g.NavLayer != ImGuiNavLayer_Main)
12420
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12421
12422
6.85k
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
12423
4.40k
    {
12424
        // Fallback manual-scroll when window has no navigable item
12425
4.40k
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12426
643
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
12427
3.75k
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12428
126
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
12429
3.63k
        else if (home_pressed)
12430
156
            SetScrollY(window, 0.0f);
12431
3.47k
        else if (end_pressed)
12432
52
            SetScrollY(window, window->ScrollMax.y);
12433
4.40k
    }
12434
2.45k
    else
12435
2.45k
    {
12436
2.45k
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
12437
2.45k
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
12438
2.45k
        float nav_scoring_rect_offset_y = 0.0f;
12439
2.45k
        if (IsKeyPressed(ImGuiKey_PageUp, true))
12440
381
        {
12441
381
            nav_scoring_rect_offset_y = -page_offset_y;
12442
381
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
12443
381
            g.NavMoveClipDir = ImGuiDir_Up;
12444
381
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
12445
381
        }
12446
2.07k
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
12447
211
        {
12448
211
            nav_scoring_rect_offset_y = +page_offset_y;
12449
211
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
12450
211
            g.NavMoveClipDir = ImGuiDir_Down;
12451
211
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
12452
211
        }
12453
1.86k
        else if (home_pressed)
12454
74
        {
12455
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
12456
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
12457
            // Preserve current horizontal position if we have any.
12458
74
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
12459
74
            if (nav_rect_rel.IsInverted())
12460
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12461
74
            g.NavMoveDir = ImGuiDir_Down;
12462
74
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12463
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12464
74
        }
12465
1.78k
        else if (end_pressed)
12466
33
        {
12467
33
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
12468
33
            if (nav_rect_rel.IsInverted())
12469
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12470
33
            g.NavMoveDir = ImGuiDir_Up;
12471
33
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12472
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12473
33
        }
12474
2.45k
        return nav_scoring_rect_offset_y;
12475
2.45k
    }
12476
4.40k
    return 0.0f;
12477
6.85k
}
12478
12479
static void ImGui::NavEndFrame()
12480
35.9k
{
12481
35.9k
    ImGuiContext& g = *GImGui;
12482
12483
    // Show CTRL+TAB list window
12484
35.9k
    if (g.NavWindowingTarget != NULL)
12485
0
        NavUpdateWindowingOverlay();
12486
12487
    // Perform wrap-around in menus
12488
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
12489
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
12490
35.9k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
12491
0
        NavUpdateCreateWrappingRequest();
12492
35.9k
}
12493
12494
static void ImGui::NavUpdateCreateWrappingRequest()
12495
0
{
12496
0
    ImGuiContext& g = *GImGui;
12497
0
    ImGuiWindow* window = g.NavWindow;
12498
12499
0
    bool do_forward = false;
12500
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
12501
0
    ImGuiDir clip_dir = g.NavMoveDir;
12502
12503
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
12504
    //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12505
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12506
0
    {
12507
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
12508
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12509
0
        {
12510
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
12511
0
            clip_dir = ImGuiDir_Up;
12512
0
        }
12513
0
        do_forward = true;
12514
0
    }
12515
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12516
0
    {
12517
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
12518
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12519
0
        {
12520
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
12521
0
            clip_dir = ImGuiDir_Down;
12522
0
        }
12523
0
        do_forward = true;
12524
0
    }
12525
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12526
0
    {
12527
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
12528
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12529
0
        {
12530
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
12531
0
            clip_dir = ImGuiDir_Left;
12532
0
        }
12533
0
        do_forward = true;
12534
0
    }
12535
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12536
0
    {
12537
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
12538
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12539
0
        {
12540
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
12541
0
            clip_dir = ImGuiDir_Right;
12542
0
        }
12543
0
        do_forward = true;
12544
0
    }
12545
0
    if (!do_forward)
12546
0
        return;
12547
0
    window->NavRectRel[g.NavLayer] = bb_rel;
12548
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12549
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12550
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
12551
0
}
12552
12553
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
12554
0
{
12555
0
    ImGuiContext& g = *GImGui;
12556
0
    IM_UNUSED(g);
12557
0
    int order = window->FocusOrder;
12558
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
12559
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
12560
0
    return order;
12561
0
}
12562
12563
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
12564
0
{
12565
0
    ImGuiContext& g = *GImGui;
12566
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
12567
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
12568
0
            return g.WindowsFocusOrder[i];
12569
0
    return NULL;
12570
0
}
12571
12572
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
12573
0
{
12574
0
    ImGuiContext& g = *GImGui;
12575
0
    IM_ASSERT(g.NavWindowingTarget);
12576
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
12577
0
        return;
12578
12579
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
12580
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
12581
0
    if (!window_target)
12582
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
12583
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
12584
0
    {
12585
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
12586
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12587
0
    }
12588
0
    g.NavWindowingToggleLayer = false;
12589
0
}
12590
12591
// Windowing management mode
12592
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
12593
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
12594
static void ImGui::NavUpdateWindowing()
12595
35.9k
{
12596
35.9k
    ImGuiContext& g = *GImGui;
12597
35.9k
    ImGuiIO& io = g.IO;
12598
12599
35.9k
    ImGuiWindow* apply_focus_window = NULL;
12600
35.9k
    bool apply_toggle_layer = false;
12601
12602
35.9k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
12603
35.9k
    bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal.
12604
35.9k
    if (!allow_windowing)
12605
0
        g.NavWindowingTarget = NULL;
12606
12607
    // Fade out
12608
35.9k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
12609
0
    {
12610
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
12611
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
12612
0
            g.NavWindowingTargetAnim = NULL;
12613
0
    }
12614
12615
    // Start CTRL+Tab or Square+L/R window selection
12616
35.9k
    const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
12617
35.9k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12618
35.9k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12619
35.9k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12620
35.9k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12621
35.9k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, 0, ImGuiInputFlags_None);
12622
35.9k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
12623
35.9k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
12624
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
12625
0
        {
12626
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
12627
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
12628
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12629
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
12630
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
12631
12632
            // Register ownership of our mods. Using ImGuiInputFlags_RouteGlobalHigh in the Shortcut() calls instead would probably be correct but may have more side-effects.
12633
0
            if (keyboard_next_window || keyboard_prev_window)
12634
0
                SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
12635
0
        }
12636
12637
    // Gamepad update
12638
35.9k
    g.NavWindowingTimer += io.DeltaTime;
12639
35.9k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
12640
0
    {
12641
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
12642
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
12643
12644
        // Select window to focus
12645
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
12646
0
        if (focus_change_dir != 0)
12647
0
        {
12648
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
12649
0
            g.NavWindowingHighlightAlpha = 1.0f;
12650
0
        }
12651
12652
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
12653
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
12654
0
        {
12655
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
12656
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
12657
0
                apply_toggle_layer = true;
12658
0
            else if (!g.NavWindowingToggleLayer)
12659
0
                apply_focus_window = g.NavWindowingTarget;
12660
0
            g.NavWindowingTarget = NULL;
12661
0
        }
12662
0
    }
12663
12664
    // Keyboard: Focus
12665
35.9k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
12666
0
    {
12667
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
12668
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
12669
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
12670
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
12671
0
        if (keyboard_next_window || keyboard_prev_window)
12672
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
12673
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
12674
0
            apply_focus_window = g.NavWindowingTarget;
12675
0
    }
12676
12677
    // Keyboard: Press and Release ALT to toggle menu layer
12678
    // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer.
12679
    // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
12680
35.9k
    if (nav_keyboard_active && IsKeyPressed(ImGuiMod_Alt, ImGuiKeyOwner_None))
12681
0
    {
12682
0
        g.NavWindowingToggleLayer = true;
12683
0
        g.NavInputSource = ImGuiInputSource_Keyboard;
12684
0
    }
12685
35.9k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
12686
0
    {
12687
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
12688
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
12689
        // We cancel toggling nav layer if an owner has claimed the key.
12690
0
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_None) == false)
12691
0
            g.NavWindowingToggleLayer = false;
12692
12693
        // Apply layer toggle on release
12694
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
12695
0
        if (IsKeyReleased(ImGuiMod_Alt) && g.NavWindowingToggleLayer)
12696
0
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
12697
0
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
12698
0
                    apply_toggle_layer = true;
12699
0
        if (!IsKeyDown(ImGuiMod_Alt))
12700
0
            g.NavWindowingToggleLayer = false;
12701
0
    }
12702
12703
    // Move window
12704
35.9k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
12705
0
    {
12706
0
        ImVec2 nav_move_dir;
12707
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
12708
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
12709
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
12710
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12711
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
12712
0
        {
12713
0
            const float NAV_MOVE_SPEED = 800.0f;
12714
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
12715
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
12716
0
            g.NavDisableMouseHover = true;
12717
0
            ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaPos);
12718
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
12719
0
            {
12720
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
12721
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
12722
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
12723
0
            }
12724
0
        }
12725
0
    }
12726
12727
    // Apply final focus
12728
35.9k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
12729
0
    {
12730
        // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
12731
        // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
12732
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
12733
0
        ClearActiveID();
12734
0
        NavRestoreHighlightAfterMove();
12735
0
        ClosePopupsOverWindow(apply_focus_window, false);
12736
0
        FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
12737
0
        apply_focus_window = g.NavWindow;
12738
0
        if (apply_focus_window->NavLastIds[0] == 0)
12739
0
            NavInitWindow(apply_focus_window, false);
12740
12741
        // If the window has ONLY a menu layer (no main layer), select it directly
12742
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
12743
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
12744
        // the target window as already been previewed once.
12745
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
12746
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
12747
        // won't be valid.
12748
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
12749
0
            g.NavLayer = ImGuiNavLayer_Menu;
12750
12751
        // Request OS level focus
12752
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
12753
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
12754
0
    }
12755
35.9k
    if (apply_focus_window)
12756
0
        g.NavWindowingTarget = NULL;
12757
12758
    // Apply menu/layer toggle
12759
35.9k
    if (apply_toggle_layer && g.NavWindow)
12760
0
    {
12761
0
        ClearActiveID();
12762
12763
        // Move to parent menu if necessary
12764
0
        ImGuiWindow* new_nav_window = g.NavWindow;
12765
0
        while (new_nav_window->ParentWindow
12766
0
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
12767
0
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
12768
0
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12769
0
            new_nav_window = new_nav_window->ParentWindow;
12770
0
        if (new_nav_window != g.NavWindow)
12771
0
        {
12772
0
            ImGuiWindow* old_nav_window = g.NavWindow;
12773
0
            FocusWindow(new_nav_window);
12774
0
            new_nav_window->NavLastChildNavWindow = old_nav_window;
12775
0
        }
12776
12777
        // Toggle layer
12778
0
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
12779
0
        if (new_nav_layer != g.NavLayer)
12780
0
        {
12781
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
12782
0
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
12783
0
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
12784
0
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
12785
0
            NavRestoreLayer(new_nav_layer);
12786
0
            NavRestoreHighlightAfterMove();
12787
0
        }
12788
0
    }
12789
35.9k
}
12790
12791
// Window has already passed the IsWindowNavFocusable()
12792
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
12793
0
{
12794
0
    if (window->Flags & ImGuiWindowFlags_Popup)
12795
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
12796
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
12797
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
12798
0
    if (window->DockNodeAsHost)
12799
0
        return "(Dock node)"; // Not normally shown to user.
12800
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
12801
0
}
12802
12803
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
12804
void ImGui::NavUpdateWindowingOverlay()
12805
0
{
12806
0
    ImGuiContext& g = *GImGui;
12807
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
12808
12809
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
12810
0
        return;
12811
12812
0
    if (g.NavWindowingListWindow == NULL)
12813
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
12814
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
12815
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
12816
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
12817
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
12818
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
12819
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
12820
0
    {
12821
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
12822
0
        IM_ASSERT(window != NULL); // Fix static analyzers
12823
0
        if (!IsWindowNavFocusable(window))
12824
0
            continue;
12825
0
        const char* label = window->Name;
12826
0
        if (label == FindRenderedTextEnd(label))
12827
0
            label = GetFallbackWindowNameForWindowingList(window);
12828
0
        Selectable(label, g.NavWindowingTarget == window);
12829
0
    }
12830
0
    End();
12831
0
    PopStyleVar();
12832
0
}
12833
12834
12835
//-----------------------------------------------------------------------------
12836
// [SECTION] DRAG AND DROP
12837
//-----------------------------------------------------------------------------
12838
12839
bool ImGui::IsDragDropActive()
12840
0
{
12841
0
    ImGuiContext& g = *GImGui;
12842
0
    return g.DragDropActive;
12843
0
}
12844
12845
void ImGui::ClearDragDrop()
12846
6
{
12847
6
    ImGuiContext& g = *GImGui;
12848
6
    g.DragDropActive = false;
12849
6
    g.DragDropPayload.Clear();
12850
6
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
12851
6
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
12852
6
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
12853
6
    g.DragDropAcceptFrameCount = -1;
12854
12855
6
    g.DragDropPayloadBufHeap.clear();
12856
6
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
12857
6
}
12858
12859
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
12860
// If the item has an identifier:
12861
// - This assume/require the item to be activated (typically via ButtonBehavior).
12862
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
12863
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
12864
// If the item has no identifier:
12865
// - Currently always assume left mouse button.
12866
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
12867
18
{
12868
18
    ImGuiContext& g = *GImGui;
12869
18
    ImGuiWindow* window = g.CurrentWindow;
12870
12871
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
12872
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
12873
18
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
12874
12875
18
    bool source_drag_active = false;
12876
18
    ImGuiID source_id = 0;
12877
18
    ImGuiID source_parent_id = 0;
12878
18
    if (!(flags & ImGuiDragDropFlags_SourceExtern))
12879
18
    {
12880
18
        source_id = g.LastItemData.ID;
12881
18
        if (source_id != 0)
12882
18
        {
12883
            // Common path: items with ID
12884
18
            if (g.ActiveId != source_id)
12885
0
                return false;
12886
18
            if (g.ActiveIdMouseButton != -1)
12887
0
                mouse_button = g.ActiveIdMouseButton;
12888
18
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
12889
0
                return false;
12890
18
            g.ActiveIdAllowOverlap = false;
12891
18
        }
12892
0
        else
12893
0
        {
12894
            // Uncommon path: items without ID
12895
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
12896
0
                return false;
12897
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
12898
0
                return false;
12899
12900
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
12901
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
12902
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
12903
0
            {
12904
0
                IM_ASSERT(0);
12905
0
                return false;
12906
0
            }
12907
12908
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
12909
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
12910
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
12911
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
12912
            // Rely on keeping other window->LastItemXXX fields intact.
12913
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
12914
0
            KeepAliveID(source_id);
12915
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id);
12916
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
12917
0
            {
12918
0
                SetActiveID(source_id, window);
12919
0
                FocusWindow(window);
12920
0
            }
12921
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
12922
0
                g.ActiveIdAllowOverlap = is_hovered;
12923
0
        }
12924
18
        if (g.ActiveId != source_id)
12925
0
            return false;
12926
18
        source_parent_id = window->IDStack.back();
12927
18
        source_drag_active = IsMouseDragging(mouse_button);
12928
12929
        // Disable navigation and key inputs while dragging + cancel existing request if any
12930
18
        SetActiveIdUsingAllKeyboardKeys();
12931
18
    }
12932
0
    else
12933
0
    {
12934
0
        window = NULL;
12935
0
        source_id = ImHashStr("#SourceExtern");
12936
0
        source_drag_active = true;
12937
0
    }
12938
12939
18
    if (source_drag_active)
12940
18
    {
12941
18
        if (!g.DragDropActive)
12942
3
        {
12943
3
            IM_ASSERT(source_id != 0);
12944
3
            ClearDragDrop();
12945
3
            ImGuiPayload& payload = g.DragDropPayload;
12946
3
            payload.SourceId = source_id;
12947
3
            payload.SourceParentId = source_parent_id;
12948
3
            g.DragDropActive = true;
12949
3
            g.DragDropSourceFlags = flags;
12950
3
            g.DragDropMouseButton = mouse_button;
12951
3
            if (payload.SourceId == g.ActiveId)
12952
3
                g.ActiveIdNoClearOnFocusLoss = true;
12953
3
        }
12954
18
        g.DragDropSourceFrameCount = g.FrameCount;
12955
18
        g.DragDropWithinSource = true;
12956
12957
18
        if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
12958
0
        {
12959
            // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
12960
            // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
12961
0
            bool ret = BeginTooltip();
12962
0
            IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
12963
0
            IM_UNUSED(ret);
12964
12965
0
            if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
12966
0
                SetWindowHiddendAndSkipItemsForCurrentFrame(g.CurrentWindow);
12967
0
        }
12968
12969
18
        if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
12970
18
            g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
12971
12972
18
        return true;
12973
18
    }
12974
0
    return false;
12975
18
}
12976
12977
void ImGui::EndDragDropSource()
12978
18
{
12979
18
    ImGuiContext& g = *GImGui;
12980
18
    IM_ASSERT(g.DragDropActive);
12981
18
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
12982
12983
18
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
12984
0
        EndTooltip();
12985
12986
    // Discard the drag if have not called SetDragDropPayload()
12987
18
    if (g.DragDropPayload.DataFrameCount == -1)
12988
0
        ClearDragDrop();
12989
18
    g.DragDropWithinSource = false;
12990
18
}
12991
12992
// Use 'cond' to choose to submit payload on drag start or every frame
12993
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
12994
18
{
12995
18
    ImGuiContext& g = *GImGui;
12996
18
    ImGuiPayload& payload = g.DragDropPayload;
12997
18
    if (cond == 0)
12998
18
        cond = ImGuiCond_Always;
12999
13000
18
    IM_ASSERT(type != NULL);
13001
18
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
13002
18
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
13003
18
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
13004
18
    IM_ASSERT(payload.SourceId != 0);                               // Not called between BeginDragDropSource() and EndDragDropSource()
13005
13006
18
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
13007
18
    {
13008
        // Copy payload
13009
18
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
13010
18
        g.DragDropPayloadBufHeap.resize(0);
13011
18
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
13012
0
        {
13013
            // Store in heap
13014
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
13015
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
13016
0
            memcpy(payload.Data, data, data_size);
13017
0
        }
13018
18
        else if (data_size > 0)
13019
18
        {
13020
            // Store locally
13021
18
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13022
18
            payload.Data = g.DragDropPayloadBufLocal;
13023
18
            memcpy(payload.Data, data, data_size);
13024
18
        }
13025
0
        else
13026
0
        {
13027
0
            payload.Data = NULL;
13028
0
        }
13029
18
        payload.DataSize = (int)data_size;
13030
18
    }
13031
18
    payload.DataFrameCount = g.FrameCount;
13032
13033
    // Return whether the payload has been accepted
13034
18
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
13035
18
}
13036
13037
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
13038
27
{
13039
27
    ImGuiContext& g = *GImGui;
13040
27
    if (!g.DragDropActive)
13041
0
        return false;
13042
13043
27
    ImGuiWindow* window = g.CurrentWindow;
13044
27
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13045
27
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
13046
27
        return false;
13047
0
    IM_ASSERT(id != 0);
13048
0
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
13049
0
        return false;
13050
0
    if (window->SkipItems)
13051
0
        return false;
13052
13053
0
    IM_ASSERT(g.DragDropWithinTarget == false);
13054
0
    g.DragDropTargetRect = bb;
13055
0
    g.DragDropTargetId = id;
13056
0
    g.DragDropWithinTarget = true;
13057
0
    return true;
13058
0
}
13059
13060
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
13061
// 1) we use LastItemRectHoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
13062
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
13063
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
13064
bool ImGui::BeginDragDropTarget()
13065
0
{
13066
0
    ImGuiContext& g = *GImGui;
13067
0
    if (!g.DragDropActive)
13068
0
        return false;
13069
13070
0
    ImGuiWindow* window = g.CurrentWindow;
13071
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
13072
0
        return false;
13073
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13074
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
13075
0
        return false;
13076
13077
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
13078
0
    ImGuiID id = g.LastItemData.ID;
13079
0
    if (id == 0)
13080
0
    {
13081
0
        id = window->GetIDFromRectangle(display_rect);
13082
0
        KeepAliveID(id);
13083
0
    }
13084
0
    if (g.DragDropPayload.SourceId == id)
13085
0
        return false;
13086
13087
0
    IM_ASSERT(g.DragDropWithinTarget == false);
13088
0
    g.DragDropTargetRect = display_rect;
13089
0
    g.DragDropTargetId = id;
13090
0
    g.DragDropWithinTarget = true;
13091
0
    return true;
13092
0
}
13093
13094
bool ImGui::IsDragDropPayloadBeingAccepted()
13095
3
{
13096
3
    ImGuiContext& g = *GImGui;
13097
3
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
13098
3
}
13099
13100
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
13101
0
{
13102
0
    ImGuiContext& g = *GImGui;
13103
0
    ImGuiWindow* window = g.CurrentWindow;
13104
0
    ImGuiPayload& payload = g.DragDropPayload;
13105
0
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
13106
0
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
13107
0
    if (type != NULL && !payload.IsDataType(type))
13108
0
        return NULL;
13109
13110
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
13111
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
13112
0
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
13113
0
    ImRect r = g.DragDropTargetRect;
13114
0
    float r_surface = r.GetWidth() * r.GetHeight();
13115
0
    if (r_surface > g.DragDropAcceptIdCurrRectSurface)
13116
0
        return NULL;
13117
13118
0
    g.DragDropAcceptFlags = flags;
13119
0
    g.DragDropAcceptIdCurr = g.DragDropTargetId;
13120
0
    g.DragDropAcceptIdCurrRectSurface = r_surface;
13121
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
13122
13123
    // Render default drop visuals
13124
0
    payload.Preview = was_accepted_previously;
13125
0
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
13126
0
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
13127
0
        window->DrawList->AddRect(r.Min - ImVec2(3.5f,3.5f), r.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
13128
13129
0
    g.DragDropAcceptFrameCount = g.FrameCount;
13130
0
    payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
13131
0
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
13132
0
        return NULL;
13133
13134
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: return payload\n", g.DragDropTargetId);
13135
0
    return &payload;
13136
0
}
13137
13138
// FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
13139
void ImGui::RenderDragDropTargetRect(const ImRect& bb)
13140
0
{
13141
0
    GetWindowDrawList()->AddRect(bb.Min - ImVec2(3.5f, 3.5f), bb.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
13142
0
}
13143
13144
const ImGuiPayload* ImGui::GetDragDropPayload()
13145
0
{
13146
0
    ImGuiContext& g = *GImGui;
13147
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
13148
0
}
13149
13150
void ImGui::EndDragDropTarget()
13151
0
{
13152
0
    ImGuiContext& g = *GImGui;
13153
0
    IM_ASSERT(g.DragDropActive);
13154
0
    IM_ASSERT(g.DragDropWithinTarget);
13155
0
    g.DragDropWithinTarget = false;
13156
13157
    // Clear drag and drop state payload right after delivery
13158
0
    if (g.DragDropPayload.Delivery)
13159
0
        ClearDragDrop();
13160
0
}
13161
13162
//-----------------------------------------------------------------------------
13163
// [SECTION] LOGGING/CAPTURING
13164
//-----------------------------------------------------------------------------
13165
// All text output from the interface can be captured into tty/file/clipboard.
13166
// By default, tree nodes are automatically opened during logging.
13167
//-----------------------------------------------------------------------------
13168
13169
// Pass text data straight to log (without being displayed)
13170
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
13171
0
{
13172
0
    if (g.LogFile)
13173
0
    {
13174
0
        g.LogBuffer.Buf.resize(0);
13175
0
        g.LogBuffer.appendfv(fmt, args);
13176
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
13177
0
    }
13178
0
    else
13179
0
    {
13180
0
        g.LogBuffer.appendfv(fmt, args);
13181
0
    }
13182
0
}
13183
13184
void ImGui::LogText(const char* fmt, ...)
13185
0
{
13186
0
    ImGuiContext& g = *GImGui;
13187
0
    if (!g.LogEnabled)
13188
0
        return;
13189
13190
0
    va_list args;
13191
0
    va_start(args, fmt);
13192
0
    LogTextV(g, fmt, args);
13193
0
    va_end(args);
13194
0
}
13195
13196
void ImGui::LogTextV(const char* fmt, va_list args)
13197
0
{
13198
0
    ImGuiContext& g = *GImGui;
13199
0
    if (!g.LogEnabled)
13200
0
        return;
13201
13202
0
    LogTextV(g, fmt, args);
13203
0
}
13204
13205
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
13206
// We split text into individual lines to add current tree level padding
13207
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
13208
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
13209
0
{
13210
0
    ImGuiContext& g = *GImGui;
13211
0
    ImGuiWindow* window = g.CurrentWindow;
13212
13213
0
    const char* prefix = g.LogNextPrefix;
13214
0
    const char* suffix = g.LogNextSuffix;
13215
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13216
13217
0
    if (!text_end)
13218
0
        text_end = FindRenderedTextEnd(text, text_end);
13219
13220
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
13221
0
    if (ref_pos)
13222
0
        g.LogLinePosY = ref_pos->y;
13223
0
    if (log_new_line)
13224
0
    {
13225
0
        LogText(IM_NEWLINE);
13226
0
        g.LogLineFirstItem = true;
13227
0
    }
13228
13229
0
    if (prefix)
13230
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
13231
13232
    // Re-adjust padding if we have popped out of our starting depth
13233
0
    if (g.LogDepthRef > window->DC.TreeDepth)
13234
0
        g.LogDepthRef = window->DC.TreeDepth;
13235
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
13236
13237
0
    const char* text_remaining = text;
13238
0
    for (;;)
13239
0
    {
13240
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
13241
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
13242
0
        const char* line_start = text_remaining;
13243
0
        const char* line_end = ImStreolRange(line_start, text_end);
13244
0
        const bool is_last_line = (line_end == text_end);
13245
0
        if (line_start != line_end || !is_last_line)
13246
0
        {
13247
0
            const int line_length = (int)(line_end - line_start);
13248
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
13249
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
13250
0
            g.LogLineFirstItem = false;
13251
0
            if (*line_end == '\n')
13252
0
            {
13253
0
                LogText(IM_NEWLINE);
13254
0
                g.LogLineFirstItem = true;
13255
0
            }
13256
0
        }
13257
0
        if (is_last_line)
13258
0
            break;
13259
0
        text_remaining = line_end + 1;
13260
0
    }
13261
13262
0
    if (suffix)
13263
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
13264
0
}
13265
13266
// Start logging/capturing text output
13267
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
13268
0
{
13269
0
    ImGuiContext& g = *GImGui;
13270
0
    ImGuiWindow* window = g.CurrentWindow;
13271
0
    IM_ASSERT(g.LogEnabled == false);
13272
0
    IM_ASSERT(g.LogFile == NULL);
13273
0
    IM_ASSERT(g.LogBuffer.empty());
13274
0
    g.LogEnabled = true;
13275
0
    g.LogType = type;
13276
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13277
0
    g.LogDepthRef = window->DC.TreeDepth;
13278
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
13279
0
    g.LogLinePosY = FLT_MAX;
13280
0
    g.LogLineFirstItem = true;
13281
0
}
13282
13283
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
13284
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
13285
0
{
13286
0
    ImGuiContext& g = *GImGui;
13287
0
    g.LogNextPrefix = prefix;
13288
0
    g.LogNextSuffix = suffix;
13289
0
}
13290
13291
void ImGui::LogToTTY(int auto_open_depth)
13292
0
{
13293
0
    ImGuiContext& g = *GImGui;
13294
0
    if (g.LogEnabled)
13295
0
        return;
13296
0
    IM_UNUSED(auto_open_depth);
13297
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13298
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
13299
0
    g.LogFile = stdout;
13300
0
#endif
13301
0
}
13302
13303
// Start logging/capturing text output to given file
13304
void ImGui::LogToFile(int auto_open_depth, const char* filename)
13305
0
{
13306
0
    ImGuiContext& g = *GImGui;
13307
0
    if (g.LogEnabled)
13308
0
        return;
13309
13310
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
13311
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
13312
    // By opening the file in binary mode "ab" we have consistent output everywhere.
13313
0
    if (!filename)
13314
0
        filename = g.IO.LogFilename;
13315
0
    if (!filename || !filename[0])
13316
0
        return;
13317
0
    ImFileHandle f = ImFileOpen(filename, "ab");
13318
0
    if (!f)
13319
0
    {
13320
0
        IM_ASSERT(0);
13321
0
        return;
13322
0
    }
13323
13324
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
13325
0
    g.LogFile = f;
13326
0
}
13327
13328
// Start logging/capturing text output to clipboard
13329
void ImGui::LogToClipboard(int auto_open_depth)
13330
0
{
13331
0
    ImGuiContext& g = *GImGui;
13332
0
    if (g.LogEnabled)
13333
0
        return;
13334
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
13335
0
}
13336
13337
void ImGui::LogToBuffer(int auto_open_depth)
13338
0
{
13339
0
    ImGuiContext& g = *GImGui;
13340
0
    if (g.LogEnabled)
13341
0
        return;
13342
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
13343
0
}
13344
13345
void ImGui::LogFinish()
13346
71.8k
{
13347
71.8k
    ImGuiContext& g = *GImGui;
13348
71.8k
    if (!g.LogEnabled)
13349
71.8k
        return;
13350
13351
0
    LogText(IM_NEWLINE);
13352
0
    switch (g.LogType)
13353
0
    {
13354
0
    case ImGuiLogType_TTY:
13355
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13356
0
        fflush(g.LogFile);
13357
0
#endif
13358
0
        break;
13359
0
    case ImGuiLogType_File:
13360
0
        ImFileClose(g.LogFile);
13361
0
        break;
13362
0
    case ImGuiLogType_Buffer:
13363
0
        break;
13364
0
    case ImGuiLogType_Clipboard:
13365
0
        if (!g.LogBuffer.empty())
13366
0
            SetClipboardText(g.LogBuffer.begin());
13367
0
        break;
13368
0
    case ImGuiLogType_None:
13369
0
        IM_ASSERT(0);
13370
0
        break;
13371
0
    }
13372
13373
0
    g.LogEnabled = false;
13374
0
    g.LogType = ImGuiLogType_None;
13375
0
    g.LogFile = NULL;
13376
0
    g.LogBuffer.clear();
13377
0
}
13378
13379
// Helper to display logging buttons
13380
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
13381
void ImGui::LogButtons()
13382
0
{
13383
0
    ImGuiContext& g = *GImGui;
13384
13385
0
    PushID("LogButtons");
13386
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13387
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
13388
#else
13389
    const bool log_to_tty = false;
13390
#endif
13391
0
    const bool log_to_file = Button("Log To File"); SameLine();
13392
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
13393
0
    PushTabStop(false);
13394
0
    SetNextItemWidth(80.0f);
13395
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
13396
0
    PopTabStop();
13397
0
    PopID();
13398
13399
    // Start logging at the end of the function so that the buttons don't appear in the log
13400
0
    if (log_to_tty)
13401
0
        LogToTTY();
13402
0
    if (log_to_file)
13403
0
        LogToFile();
13404
0
    if (log_to_clipboard)
13405
0
        LogToClipboard();
13406
0
}
13407
13408
13409
//-----------------------------------------------------------------------------
13410
// [SECTION] SETTINGS
13411
//-----------------------------------------------------------------------------
13412
// - UpdateSettings() [Internal]
13413
// - MarkIniSettingsDirty() [Internal]
13414
// - FindSettingsHandler() [Internal]
13415
// - ClearIniSettings() [Internal]
13416
// - LoadIniSettingsFromDisk()
13417
// - LoadIniSettingsFromMemory()
13418
// - SaveIniSettingsToDisk()
13419
// - SaveIniSettingsToMemory()
13420
//-----------------------------------------------------------------------------
13421
// - CreateNewWindowSettings() [Internal]
13422
// - FindWindowSettingsByID() [Internal]
13423
// - FindWindowSettingsByWindow() [Internal]
13424
// - ClearWindowSettings() [Internal]
13425
// - WindowSettingsHandler_***() [Internal]
13426
//-----------------------------------------------------------------------------
13427
13428
// Called by NewFrame()
13429
void ImGui::UpdateSettings()
13430
35.9k
{
13431
    // Load settings on first frame (if not explicitly loaded manually before)
13432
35.9k
    ImGuiContext& g = *GImGui;
13433
35.9k
    if (!g.SettingsLoaded)
13434
1
    {
13435
1
        IM_ASSERT(g.SettingsWindows.empty());
13436
1
        if (g.IO.IniFilename)
13437
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
13438
1
        g.SettingsLoaded = true;
13439
1
    }
13440
13441
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
13442
35.9k
    if (g.SettingsDirtyTimer > 0.0f)
13443
1.20k
    {
13444
1.20k
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
13445
1.20k
        if (g.SettingsDirtyTimer <= 0.0f)
13446
4
        {
13447
4
            if (g.IO.IniFilename != NULL)
13448
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
13449
4
            else
13450
4
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
13451
4
            g.SettingsDirtyTimer = 0.0f;
13452
4
        }
13453
1.20k
    }
13454
35.9k
}
13455
13456
void ImGui::MarkIniSettingsDirty()
13457
0
{
13458
0
    ImGuiContext& g = *GImGui;
13459
0
    if (g.SettingsDirtyTimer <= 0.0f)
13460
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
13461
0
}
13462
13463
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
13464
6.58k
{
13465
6.58k
    ImGuiContext& g = *GImGui;
13466
6.58k
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
13467
11
        if (g.SettingsDirtyTimer <= 0.0f)
13468
4
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
13469
6.58k
}
13470
13471
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
13472
2
{
13473
2
    ImGuiContext& g = *GImGui;
13474
2
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
13475
2
    g.SettingsHandlers.push_back(*handler);
13476
2
}
13477
13478
void ImGui::RemoveSettingsHandler(const char* type_name)
13479
0
{
13480
0
    ImGuiContext& g = *GImGui;
13481
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
13482
0
        g.SettingsHandlers.erase(handler);
13483
0
}
13484
13485
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
13486
2
{
13487
2
    ImGuiContext& g = *GImGui;
13488
2
    const ImGuiID type_hash = ImHashStr(type_name);
13489
3
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13490
1
        if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
13491
0
            return &g.SettingsHandlers[handler_n];
13492
2
    return NULL;
13493
2
}
13494
13495
// Clear all settings (windows, tables, docking etc.)
13496
void ImGui::ClearIniSettings()
13497
0
{
13498
0
    ImGuiContext& g = *GImGui;
13499
0
    g.SettingsIniData.clear();
13500
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13501
0
        if (g.SettingsHandlers[handler_n].ClearAllFn)
13502
0
            g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]);
13503
0
}
13504
13505
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
13506
0
{
13507
0
    size_t file_data_size = 0;
13508
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
13509
0
    if (!file_data)
13510
0
        return;
13511
0
    if (file_data_size > 0)
13512
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
13513
0
    IM_FREE(file_data);
13514
0
}
13515
13516
// Zero-tolerance, no error reporting, cheap .ini parsing
13517
// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty!
13518
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
13519
0
{
13520
0
    ImGuiContext& g = *GImGui;
13521
0
    IM_ASSERT(g.Initialized);
13522
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
13523
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
13524
13525
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
13526
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
13527
0
    if (ini_size == 0)
13528
0
        ini_size = strlen(ini_data);
13529
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
13530
0
    char* const buf = g.SettingsIniData.Buf.Data;
13531
0
    char* const buf_end = buf + ini_size;
13532
0
    memcpy(buf, ini_data, ini_size);
13533
0
    buf_end[0] = 0;
13534
13535
    // Call pre-read handlers
13536
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
13537
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13538
0
        if (g.SettingsHandlers[handler_n].ReadInitFn)
13539
0
            g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]);
13540
13541
0
    void* entry_data = NULL;
13542
0
    ImGuiSettingsHandler* entry_handler = NULL;
13543
13544
0
    char* line_end = NULL;
13545
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
13546
0
    {
13547
        // Skip new lines markers, then find end of the line
13548
0
        while (*line == '\n' || *line == '\r')
13549
0
            line++;
13550
0
        line_end = line;
13551
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
13552
0
            line_end++;
13553
0
        line_end[0] = 0;
13554
0
        if (line[0] == ';')
13555
0
            continue;
13556
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
13557
0
        {
13558
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
13559
0
            line_end[-1] = 0;
13560
0
            const char* name_end = line_end - 1;
13561
0
            const char* type_start = line + 1;
13562
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
13563
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
13564
0
            if (!type_end || !name_start)
13565
0
                continue;
13566
0
            *type_end = 0; // Overwrite first ']'
13567
0
            name_start++;  // Skip second '['
13568
0
            entry_handler = FindSettingsHandler(type_start);
13569
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
13570
0
        }
13571
0
        else if (entry_handler != NULL && entry_data != NULL)
13572
0
        {
13573
            // Let type handler parse the line
13574
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
13575
0
        }
13576
0
    }
13577
0
    g.SettingsLoaded = true;
13578
13579
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
13580
0
    memcpy(buf, ini_data, ini_size);
13581
13582
    // Call post-read handlers
13583
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13584
0
        if (g.SettingsHandlers[handler_n].ApplyAllFn)
13585
0
            g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]);
13586
0
}
13587
13588
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
13589
0
{
13590
0
    ImGuiContext& g = *GImGui;
13591
0
    g.SettingsDirtyTimer = 0.0f;
13592
0
    if (!ini_filename)
13593
0
        return;
13594
13595
0
    size_t ini_data_size = 0;
13596
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
13597
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
13598
0
    if (!f)
13599
0
        return;
13600
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
13601
0
    ImFileClose(f);
13602
0
}
13603
13604
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
13605
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
13606
0
{
13607
0
    ImGuiContext& g = *GImGui;
13608
0
    g.SettingsDirtyTimer = 0.0f;
13609
0
    g.SettingsIniData.Buf.resize(0);
13610
0
    g.SettingsIniData.Buf.push_back(0);
13611
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13612
0
    {
13613
0
        ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
13614
0
        handler->WriteAllFn(&g, handler, &g.SettingsIniData);
13615
0
    }
13616
0
    if (out_size)
13617
0
        *out_size = (size_t)g.SettingsIniData.size();
13618
0
    return g.SettingsIniData.c_str();
13619
0
}
13620
13621
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
13622
0
{
13623
0
    ImGuiContext& g = *GImGui;
13624
13625
0
    if (g.IO.ConfigDebugIniSettings == false)
13626
0
    {
13627
        // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
13628
        // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
13629
0
        if (const char* p = strstr(name, "###"))
13630
0
            name = p;
13631
0
    }
13632
0
    const size_t name_len = strlen(name);
13633
13634
    // Allocate chunk
13635
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
13636
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
13637
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
13638
0
    settings->ID = ImHashStr(name, name_len);
13639
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
13640
13641
0
    return settings;
13642
0
}
13643
13644
// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
13645
// This is called once per window .ini entry + once per newly instantiated window.
13646
ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
13647
2
{
13648
2
    ImGuiContext& g = *GImGui;
13649
2
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13650
0
        if (settings->ID == id && !settings->WantDelete)
13651
0
            return settings;
13652
2
    return NULL;
13653
2
}
13654
13655
// This is faster if you are holding on a Window already as we don't need to perform a search.
13656
ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
13657
2
{
13658
2
    ImGuiContext& g = *GImGui;
13659
2
    if (window->SettingsOffset != -1)
13660
0
        return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
13661
2
    return FindWindowSettingsByID(window->ID);
13662
2
}
13663
13664
// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
13665
void ImGui::ClearWindowSettings(const char* name)
13666
0
{
13667
    //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
13668
0
    ImGuiContext& g = *GImGui;
13669
0
    ImGuiWindow* window = FindWindowByName(name);
13670
0
    if (window != NULL)
13671
0
    {
13672
0
        window->Flags |= ImGuiWindowFlags_NoSavedSettings;
13673
0
        InitOrLoadWindowSettings(window, NULL);
13674
0
        if (window->DockId != 0)
13675
0
            DockContextProcessUndockWindow(&g, window, true);
13676
0
    }
13677
0
    if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
13678
0
        settings->WantDelete = true;
13679
0
}
13680
13681
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13682
0
{
13683
0
    ImGuiContext& g = *ctx;
13684
0
    for (int i = 0; i != g.Windows.Size; i++)
13685
0
        g.Windows[i]->SettingsOffset = -1;
13686
0
    g.SettingsWindows.clear();
13687
0
}
13688
13689
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
13690
0
{
13691
0
    ImGuiID id = ImHashStr(name);
13692
0
    ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
13693
0
    if (settings)
13694
0
        *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
13695
0
    else
13696
0
        settings = ImGui::CreateNewWindowSettings(name);
13697
0
    settings->ID = id;
13698
0
    settings->WantApply = true;
13699
0
    return (void*)settings;
13700
0
}
13701
13702
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
13703
0
{
13704
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
13705
0
    int x, y;
13706
0
    int i;
13707
0
    ImU32 u1;
13708
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
13709
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
13710
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
13711
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
13712
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
13713
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
13714
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
13715
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
13716
0
}
13717
13718
// Apply to existing windows (if any)
13719
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13720
0
{
13721
0
    ImGuiContext& g = *ctx;
13722
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13723
0
        if (settings->WantApply)
13724
0
        {
13725
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
13726
0
                ApplyWindowSettings(window, settings);
13727
0
            settings->WantApply = false;
13728
0
        }
13729
0
}
13730
13731
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
13732
0
{
13733
    // Gather data from windows that were active during this session
13734
    // (if a window wasn't opened in this session we preserve its settings)
13735
0
    ImGuiContext& g = *ctx;
13736
0
    for (int i = 0; i != g.Windows.Size; i++)
13737
0
    {
13738
0
        ImGuiWindow* window = g.Windows[i];
13739
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
13740
0
            continue;
13741
13742
0
        ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
13743
0
        if (!settings)
13744
0
        {
13745
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
13746
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
13747
0
        }
13748
0
        IM_ASSERT(settings->ID == window->ID);
13749
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
13750
0
        settings->Size = ImVec2ih(window->SizeFull);
13751
0
        settings->ViewportId = window->ViewportId;
13752
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
13753
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
13754
0
        settings->DockId = window->DockId;
13755
0
        settings->ClassId = window->WindowClass.ClassId;
13756
0
        settings->DockOrder = window->DockOrder;
13757
0
        settings->Collapsed = window->Collapsed;
13758
0
        settings->WantDelete = false;
13759
0
    }
13760
13761
    // Write to text buffer
13762
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
13763
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13764
0
    {
13765
0
        if (settings->WantDelete)
13766
0
            continue;
13767
0
        const char* settings_name = settings->GetName();
13768
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
13769
0
        if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13770
0
        {
13771
0
            buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
13772
0
            buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
13773
0
        }
13774
0
        if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13775
0
            buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
13776
0
        if (settings->Size.x != 0 || settings->Size.y != 0)
13777
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
13778
0
        buf->appendf("Collapsed=%d\n", settings->Collapsed);
13779
0
        if (settings->DockId != 0)
13780
0
        {
13781
            //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
13782
0
            if (settings->DockOrder == -1)
13783
0
                buf->appendf("DockId=0x%08X\n", settings->DockId);
13784
0
            else
13785
0
                buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
13786
0
            if (settings->ClassId != 0)
13787
0
                buf->appendf("ClassId=0x%08X\n", settings->ClassId);
13788
0
        }
13789
0
        buf->append("\n");
13790
0
    }
13791
0
}
13792
13793
13794
//-----------------------------------------------------------------------------
13795
// [SECTION] LOCALIZATION
13796
//-----------------------------------------------------------------------------
13797
13798
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
13799
1
{
13800
1
    ImGuiContext& g = *GImGui;
13801
9
    for (int n = 0; n < count; n++)
13802
8
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
13803
1
}
13804
13805
13806
//-----------------------------------------------------------------------------
13807
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
13808
//-----------------------------------------------------------------------------
13809
// - GetMainViewport()
13810
// - FindViewportByID()
13811
// - FindViewportByPlatformHandle()
13812
// - SetCurrentViewport() [Internal]
13813
// - SetWindowViewport() [Internal]
13814
// - GetWindowAlwaysWantOwnViewport() [Internal]
13815
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
13816
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
13817
// - TranslateWindowsInViewport() [Internal]
13818
// - ScaleWindowsInViewport() [Internal]
13819
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
13820
// - UpdateViewportsNewFrame() [Internal]
13821
// - UpdateViewportsEndFrame() [Internal]
13822
// - AddUpdateViewport() [Internal]
13823
// - WindowSelectViewport() [Internal]
13824
// - WindowSyncOwnedViewport() [Internal]
13825
// - UpdatePlatformWindows()
13826
// - RenderPlatformWindowsDefault()
13827
// - FindPlatformMonitorForPos() [Internal]
13828
// - FindPlatformMonitorForRect() [Internal]
13829
// - UpdateViewportPlatformMonitor() [Internal]
13830
// - DestroyPlatformWindow() [Internal]
13831
// - DestroyPlatformWindows()
13832
//-----------------------------------------------------------------------------
13833
13834
ImGuiViewport* ImGui::GetMainViewport()
13835
107k
{
13836
107k
    ImGuiContext& g = *GImGui;
13837
107k
    return g.Viewports[0];
13838
107k
}
13839
13840
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
13841
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
13842
35.9k
{
13843
35.9k
    ImGuiContext& g = *GImGui;
13844
35.9k
    for (int n = 0; n < g.Viewports.Size; n++)
13845
35.9k
        if (g.Viewports[n]->ID == id)
13846
35.9k
            return g.Viewports[n];
13847
0
    return NULL;
13848
35.9k
}
13849
13850
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
13851
0
{
13852
0
    ImGuiContext& g = *GImGui;
13853
0
    for (int i = 0; i != g.Viewports.Size; i++)
13854
0
        if (g.Viewports[i]->PlatformHandle == platform_handle)
13855
0
            return g.Viewports[i];
13856
0
    return NULL;
13857
0
}
13858
13859
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
13860
215k
{
13861
215k
    ImGuiContext& g = *GImGui;
13862
215k
    (void)current_window;
13863
13864
215k
    if (viewport)
13865
179k
        viewport->LastFrameActive = g.FrameCount;
13866
215k
    if (g.CurrentViewport == viewport)
13867
143k
        return;
13868
71.8k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
13869
71.8k
    g.CurrentViewport = viewport;
13870
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
13871
13872
    // Notify platform layer of viewport changes
13873
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
13874
71.8k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
13875
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
13876
71.8k
}
13877
13878
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
13879
107k
{
13880
    // Abandon viewport
13881
107k
    if (window->ViewportOwned && window->Viewport->Window == window)
13882
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
13883
13884
107k
    window->Viewport = viewport;
13885
107k
    window->ViewportId = viewport->ID;
13886
107k
    window->ViewportOwned = (viewport->Window == window);
13887
107k
}
13888
13889
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
13890
0
{
13891
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
13892
0
    ImGuiContext& g = *GImGui;
13893
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
13894
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
13895
0
            if (!window->DockIsActive)
13896
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
13897
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
13898
0
                        return true;
13899
0
    return false;
13900
0
}
13901
13902
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
13903
0
{
13904
0
    ImGuiContext& g = *GImGui;
13905
0
    if (window->Viewport == viewport)
13906
0
        return false;
13907
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
13908
0
        return false;
13909
0
    if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
13910
0
        return false;
13911
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
13912
0
        return false;
13913
0
    if (GetWindowAlwaysWantOwnViewport(window))
13914
0
        return false;
13915
13916
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
13917
0
    for (int n = 0; n < g.Windows.Size; n++)
13918
0
    {
13919
0
        ImGuiWindow* window_behind = g.Windows[n];
13920
0
        if (window_behind == window)
13921
0
            break;
13922
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
13923
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
13924
0
                return false;
13925
0
    }
13926
13927
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
13928
0
    ImGuiViewportP* old_viewport = window->Viewport;
13929
0
    if (window->ViewportOwned)
13930
0
        for (int n = 0; n < g.Windows.Size; n++)
13931
0
            if (g.Windows[n]->Viewport == old_viewport)
13932
0
                SetWindowViewport(g.Windows[n], viewport);
13933
0
    SetWindowViewport(window, viewport);
13934
0
    BringWindowToDisplayFront(window);
13935
13936
0
    return true;
13937
0
}
13938
13939
// FIXME: handle 0 to N host viewports
13940
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
13941
0
{
13942
0
    ImGuiContext& g = *GImGui;
13943
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
13944
0
}
13945
13946
// Translate Dear ImGui windows when a Host Viewport has been moved
13947
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
13948
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
13949
0
{
13950
0
    ImGuiContext& g = *GImGui;
13951
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
13952
13953
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
13954
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
13955
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
13956
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
13957
    // and so the window will appear to teleport when releasing the mouse.
13958
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
13959
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
13960
0
    ImVec2 delta_pos = new_pos - old_pos;
13961
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++) // FIXME-OPT
13962
0
        if (translate_all_windows || (g.Windows[window_n]->Viewport == viewport && test_still_fit_rect.Contains(g.Windows[window_n]->Rect())))
13963
0
            TranslateWindow(g.Windows[window_n], delta_pos);
13964
0
}
13965
13966
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
13967
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
13968
0
{
13969
0
    ImGuiContext& g = *GImGui;
13970
0
    if (viewport->Window)
13971
0
    {
13972
0
        ScaleWindow(viewport->Window, scale);
13973
0
    }
13974
0
    else
13975
0
    {
13976
0
        for (int i = 0; i != g.Windows.Size; i++)
13977
0
            if (g.Windows[i]->Viewport == viewport)
13978
0
                ScaleWindow(g.Windows[i], scale);
13979
0
    }
13980
0
}
13981
13982
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
13983
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
13984
// B) It requires Platform_GetWindowFocus to be implemented by backend.
13985
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
13986
0
{
13987
0
    ImGuiContext& g = *GImGui;
13988
0
    ImGuiViewportP* best_candidate = NULL;
13989
0
    for (int n = 0; n < g.Viewports.Size; n++)
13990
0
    {
13991
0
        ImGuiViewportP* viewport = g.Viewports[n];
13992
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
13993
0
            if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
13994
0
                best_candidate = viewport;
13995
0
    }
13996
0
    return best_candidate;
13997
0
}
13998
13999
// Update viewports and monitor infos
14000
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
14001
static void ImGui::UpdateViewportsNewFrame()
14002
35.9k
{
14003
35.9k
    ImGuiContext& g = *GImGui;
14004
35.9k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
14005
14006
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
14007
    // Update Focused status
14008
35.9k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
14009
35.9k
    if (viewports_enabled)
14010
0
    {
14011
0
        ImGuiViewportP* focused_viewport = NULL;
14012
0
        for (int n = 0; n < g.Viewports.Size; n++)
14013
0
        {
14014
0
            ImGuiViewportP* viewport = g.Viewports[n];
14015
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
14016
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
14017
0
            {
14018
0
                bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
14019
0
                if (is_minimized)
14020
0
                    viewport->Flags |= ImGuiViewportFlags_IsMinimized;
14021
0
                else
14022
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
14023
0
            }
14024
14025
            // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
14026
            // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
14027
0
            if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
14028
0
            {
14029
0
                bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
14030
0
                if (is_focused)
14031
0
                    viewport->Flags |= ImGuiViewportFlags_IsFocused;
14032
0
                else
14033
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
14034
0
                if (is_focused)
14035
0
                    focused_viewport = viewport;
14036
0
            }
14037
0
        }
14038
14039
        // Focused viewport has changed?
14040
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
14041
0
        {
14042
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID);
14043
0
            const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
14044
0
            const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
14045
14046
            // Store a tag so we can infer z-order easily from all our windows
14047
            // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
14048
            // will keep the front most stamp instead of losing it back to their parent viewport.
14049
0
            if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
14050
0
                focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
14051
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
14052
14053
            // Focus associated dear imgui window
14054
            // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
14055
            // - if focus didn't happen because we destroyed another window (#6462)
14056
            // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
14057
0
            const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
14058
0
            if (apply_imgui_focus_on_focused_viewport)
14059
0
            {
14060
0
                focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
14061
0
                ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
14062
0
                if (focused_viewport->Window != NULL)
14063
0
                    FocusWindow(focused_viewport->Window, focus_request_flags);
14064
0
                else if (focused_viewport->LastFocusedHadNavWindow)
14065
0
                    FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
14066
0
                else
14067
0
                    FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
14068
0
            }
14069
0
        }
14070
0
        if (focused_viewport)
14071
0
            focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
14072
0
    }
14073
14074
    // Create/update main viewport with current platform position.
14075
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
14076
35.9k
    ImGuiViewportP* main_viewport = g.Viewports[0];
14077
35.9k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
14078
35.9k
    IM_ASSERT(main_viewport->Window == NULL);
14079
35.9k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
14080
35.9k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
14081
35.9k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
14082
0
    {
14083
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
14084
0
        main_viewport_size = main_viewport->Size;
14085
0
    }
14086
35.9k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
14087
14088
35.9k
    g.CurrentDpiScale = 0.0f;
14089
35.9k
    g.CurrentViewport = NULL;
14090
35.9k
    g.MouseViewport = NULL;
14091
71.8k
    for (int n = 0; n < g.Viewports.Size; n++)
14092
35.9k
    {
14093
35.9k
        ImGuiViewportP* viewport = g.Viewports[n];
14094
35.9k
        viewport->Idx = n;
14095
14096
        // Erase unused viewports
14097
35.9k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
14098
0
        {
14099
0
            DestroyViewport(viewport);
14100
0
            n--;
14101
0
            continue;
14102
0
        }
14103
14104
35.9k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
14105
35.9k
        if (viewports_enabled)
14106
0
        {
14107
            // Update Position and Size (from Platform Window to ImGui) if requested.
14108
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
14109
0
            if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
14110
0
            {
14111
                // Viewport->WorkPos and WorkSize will be updated below
14112
0
                if (viewport->PlatformRequestMove)
14113
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
14114
0
                if (viewport->PlatformRequestResize)
14115
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
14116
0
            }
14117
0
        }
14118
14119
        // Update/copy monitor info
14120
35.9k
        UpdateViewportPlatformMonitor(viewport);
14121
14122
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
14123
35.9k
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
14124
35.9k
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
14125
35.9k
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
14126
35.9k
        viewport->UpdateWorkRect();
14127
14128
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
14129
35.9k
        viewport->Alpha = 1.0f;
14130
14131
        // Translate Dear ImGui windows when a Host Viewport has been moved
14132
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14133
35.9k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
14134
35.9k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
14135
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
14136
14137
        // Update DPI scale
14138
35.9k
        float new_dpi_scale;
14139
35.9k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
14140
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
14141
35.9k
        else if (viewport->PlatformMonitor != -1)
14142
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14143
35.9k
        else
14144
35.9k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
14145
35.9k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
14146
0
        {
14147
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
14148
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
14149
0
                ScaleWindowsInViewport(viewport, scale_factor);
14150
            //if (viewport == GetMainViewport())
14151
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
14152
14153
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
14154
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
14155
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
14156
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
14157
            //    g.ActiveIdClickOffset = ImFloor(g.ActiveIdClickOffset * scale_factor);
14158
0
        }
14159
35.9k
        viewport->DpiScale = new_dpi_scale;
14160
35.9k
    }
14161
14162
    // Update fallback monitor
14163
35.9k
    if (g.PlatformIO.Monitors.Size == 0)
14164
35.9k
    {
14165
35.9k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
14166
35.9k
        monitor->MainPos = main_viewport->Pos;
14167
35.9k
        monitor->MainSize = main_viewport->Size;
14168
35.9k
        monitor->WorkPos = main_viewport->WorkPos;
14169
35.9k
        monitor->WorkSize = main_viewport->WorkSize;
14170
35.9k
        monitor->DpiScale = main_viewport->DpiScale;
14171
35.9k
    }
14172
14173
35.9k
    if (!viewports_enabled)
14174
35.9k
    {
14175
35.9k
        g.MouseViewport = main_viewport;
14176
35.9k
        return;
14177
35.9k
    }
14178
14179
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
14180
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
14181
0
    ImGuiViewportP* viewport_hovered = NULL;
14182
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
14183
0
    {
14184
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
14185
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14186
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
14187
0
    }
14188
0
    else
14189
0
    {
14190
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
14191
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14192
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
14193
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
14194
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
14195
0
    }
14196
0
    if (viewport_hovered != NULL)
14197
0
        g.MouseLastHoveredViewport = viewport_hovered;
14198
0
    else if (g.MouseLastHoveredViewport == NULL)
14199
0
        g.MouseLastHoveredViewport = g.Viewports[0];
14200
14201
    // Update mouse reference viewport
14202
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
14203
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
14204
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
14205
0
        g.MouseViewport = g.MovingWindow->Viewport;
14206
0
    else
14207
0
        g.MouseViewport = g.MouseLastHoveredViewport;
14208
14209
    // When dragging something, always refer to the last hovered viewport.
14210
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
14211
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
14212
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
14213
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
14214
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
14215
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
14216
0
        viewport_hovered = g.MouseLastHoveredViewport;
14217
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
14218
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14219
0
            g.MouseViewport = viewport_hovered;
14220
14221
0
    IM_ASSERT(g.MouseViewport != NULL);
14222
0
}
14223
14224
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
14225
static void ImGui::UpdateViewportsEndFrame()
14226
35.9k
{
14227
35.9k
    ImGuiContext& g = *GImGui;
14228
35.9k
    g.PlatformIO.Viewports.resize(0);
14229
71.8k
    for (int i = 0; i < g.Viewports.Size; i++)
14230
35.9k
    {
14231
35.9k
        ImGuiViewportP* viewport = g.Viewports[i];
14232
35.9k
        viewport->LastPos = viewport->Pos;
14233
35.9k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
14234
0
            if (i > 0) // Always include main viewport in the list
14235
0
                continue;
14236
35.9k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
14237
0
            continue;
14238
35.9k
        if (i > 0)
14239
35.9k
            IM_ASSERT(viewport->Window != NULL);
14240
35.9k
        g.PlatformIO.Viewports.push_back(viewport);
14241
35.9k
    }
14242
35.9k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
14243
35.9k
}
14244
14245
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
14246
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
14247
35.9k
{
14248
35.9k
    ImGuiContext& g = *GImGui;
14249
35.9k
    IM_ASSERT(id != 0);
14250
14251
35.9k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
14252
35.9k
    if (window != NULL)
14253
0
    {
14254
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
14255
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
14256
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
14257
0
            flags |= ImGuiViewportFlags_NoInputs;
14258
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
14259
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14260
0
    }
14261
14262
35.9k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
14263
35.9k
    if (viewport)
14264
35.9k
    {
14265
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
14266
35.9k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14267
35.9k
            viewport->Pos = pos;
14268
35.9k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14269
35.9k
            viewport->Size = size;
14270
35.9k
        viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
14271
35.9k
    }
14272
0
    else
14273
0
    {
14274
        // New viewport
14275
0
        viewport = IM_NEW(ImGuiViewportP)();
14276
0
        viewport->ID = id;
14277
0
        viewport->Idx = g.Viewports.Size;
14278
0
        viewport->Pos = viewport->LastPos = pos;
14279
0
        viewport->Size = size;
14280
0
        viewport->Flags = flags;
14281
0
        UpdateViewportPlatformMonitor(viewport);
14282
0
        g.Viewports.push_back(viewport);
14283
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
14284
14285
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
14286
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
14287
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
14288
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
14289
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
14290
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
14291
14292
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
14293
        // This is so we can select an appropriate font size on the first frame of our window lifetime
14294
0
        if (viewport->PlatformMonitor != -1)
14295
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14296
0
    }
14297
14298
35.9k
    viewport->Window = window;
14299
35.9k
    viewport->LastFrameActive = g.FrameCount;
14300
35.9k
    viewport->UpdateWorkRect();
14301
35.9k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
14302
14303
35.9k
    if (window != NULL)
14304
0
        window->ViewportOwned = true;
14305
14306
35.9k
    return viewport;
14307
35.9k
}
14308
14309
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
14310
0
{
14311
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
14312
0
    ImGuiContext& g = *GImGui;
14313
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
14314
0
    {
14315
0
        ImGuiWindow* window = g.Windows[window_n];
14316
0
        if (window->Viewport != viewport)
14317
0
            continue;
14318
0
        window->Viewport = NULL;
14319
0
        window->ViewportOwned = false;
14320
0
    }
14321
0
    if (viewport == g.MouseLastHoveredViewport)
14322
0
        g.MouseLastHoveredViewport = NULL;
14323
14324
    // Destroy
14325
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14326
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
14327
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
14328
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
14329
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
14330
0
    IM_DELETE(viewport);
14331
0
}
14332
14333
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
14334
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
14335
107k
{
14336
107k
    ImGuiContext& g = *GImGui;
14337
107k
    ImGuiWindowFlags flags = window->Flags;
14338
107k
    window->ViewportAllowPlatformMonitorExtend = -1;
14339
14340
    // Restore main viewport if multi-viewport is not supported by the backend
14341
107k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
14342
107k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14343
107k
    {
14344
107k
        SetWindowViewport(window, main_viewport);
14345
107k
        return;
14346
107k
    }
14347
0
    window->ViewportOwned = false;
14348
14349
    // Appearing popups reset their viewport so they can inherit again
14350
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
14351
0
    {
14352
0
        window->Viewport = NULL;
14353
0
        window->ViewportId = 0;
14354
0
    }
14355
14356
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
14357
0
    {
14358
        // By default inherit from parent window
14359
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
14360
0
            window->Viewport = window->ParentWindow->Viewport;
14361
14362
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
14363
0
        if (window->Viewport == NULL && window->ViewportId != 0)
14364
0
        {
14365
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
14366
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
14367
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
14368
0
        }
14369
0
    }
14370
14371
0
    bool lock_viewport = false;
14372
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
14373
0
    {
14374
        // Code explicitly request a viewport
14375
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
14376
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
14377
0
        lock_viewport = true;
14378
0
    }
14379
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
14380
0
    {
14381
        // Always inherit viewport from parent window
14382
0
        if (window->DockNode && window->DockNode->HostWindow)
14383
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
14384
0
        window->Viewport = window->ParentWindow->Viewport;
14385
0
    }
14386
0
    else if (window->DockNode && window->DockNode->HostWindow)
14387
0
    {
14388
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
14389
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
14390
0
    }
14391
0
    else if (flags & ImGuiWindowFlags_Tooltip)
14392
0
    {
14393
0
        window->Viewport = g.MouseViewport;
14394
0
    }
14395
0
    else if (GetWindowAlwaysWantOwnViewport(window))
14396
0
    {
14397
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14398
0
    }
14399
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
14400
0
    {
14401
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
14402
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14403
0
    }
14404
0
    else
14405
0
    {
14406
        // Merge into host viewport?
14407
        // We cannot test window->ViewportOwned as it set lower in the function.
14408
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
14409
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
14410
0
        if (try_to_merge_into_host_viewport)
14411
0
            UpdateTryMergeWindowIntoHostViewports(window);
14412
0
    }
14413
14414
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
14415
0
    if (window->Viewport == NULL)
14416
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
14417
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14418
14419
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
14420
0
    if (!lock_viewport)
14421
0
    {
14422
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
14423
0
        {
14424
            // We need to take account of the possibility that mouse may become invalid.
14425
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
14426
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
14427
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
14428
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
14429
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
14430
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
14431
0
            else
14432
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14433
0
        }
14434
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
14435
0
        {
14436
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
14437
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
14438
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
14439
0
            {
14440
                // Steal/transfer ownership
14441
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
14442
0
                window->Viewport->Window = window;
14443
0
                window->Viewport->ID = window->ID;
14444
0
                window->Viewport->LastNameHash = 0;
14445
0
            }
14446
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
14447
0
            {
14448
                // New viewport
14449
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
14450
0
            }
14451
0
        }
14452
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
14453
0
        {
14454
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
14455
            // Child windows are kept contained within their parent.
14456
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14457
0
        }
14458
0
    }
14459
14460
    // Update flags
14461
0
    window->ViewportOwned = (window == window->Viewport->Window);
14462
0
    window->ViewportId = window->Viewport->ID;
14463
14464
    // If the OS window has a title bar, hide our imgui title bar
14465
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
14466
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
14467
0
}
14468
14469
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
14470
0
{
14471
0
    ImGuiContext& g = *GImGui;
14472
14473
0
    bool viewport_rect_changed = false;
14474
14475
    // Synchronize window --> viewport in most situations
14476
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
14477
0
    if (window->Viewport->PlatformRequestMove)
14478
0
    {
14479
0
        window->Pos = window->Viewport->Pos;
14480
0
        MarkIniSettingsDirty(window);
14481
0
    }
14482
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
14483
0
    {
14484
0
        viewport_rect_changed = true;
14485
0
        window->Viewport->Pos = window->Pos;
14486
0
    }
14487
14488
0
    if (window->Viewport->PlatformRequestResize)
14489
0
    {
14490
0
        window->Size = window->SizeFull = window->Viewport->Size;
14491
0
        MarkIniSettingsDirty(window);
14492
0
    }
14493
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
14494
0
    {
14495
0
        viewport_rect_changed = true;
14496
0
        window->Viewport->Size = window->Size;
14497
0
    }
14498
0
    window->Viewport->UpdateWorkRect();
14499
14500
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
14501
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
14502
0
    if (viewport_rect_changed)
14503
0
        UpdateViewportPlatformMonitor(window->Viewport);
14504
14505
    // Update common viewport flags
14506
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
14507
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
14508
0
    ImGuiWindowFlags window_flags = window->Flags;
14509
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
14510
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
14511
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
14512
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
14513
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
14514
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
14515
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
14516
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
14517
14518
    // Not correct to set modal as topmost because:
14519
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
14520
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
14521
    //if (flags & ImGuiWindowFlags_Modal)
14522
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
14523
14524
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
14525
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
14526
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
14527
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
14528
0
    if (is_short_lived_floating_window && !is_modal)
14529
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
14530
14531
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
14532
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
14533
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
14534
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
14535
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
14536
14537
    // We can also tell the backend that clearing the platform window won't be necessary,
14538
    // as our window background is filling the viewport and we have disabled BgAlpha.
14539
    // FIXME: Work on support for per-viewport transparency (#2766)
14540
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
14541
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
14542
14543
0
    window->Viewport->Flags = viewport_flags;
14544
14545
    // Update parent viewport ID
14546
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
14547
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
14548
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
14549
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
14550
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
14551
0
    else
14552
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
14553
0
}
14554
14555
// Called by user at the end of the main loop, after EndFrame()
14556
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
14557
void ImGui::UpdatePlatformWindows()
14558
0
{
14559
0
    ImGuiContext& g = *GImGui;
14560
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
14561
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
14562
0
    g.FrameCountPlatformEnded = g.FrameCount;
14563
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14564
0
        return;
14565
14566
    // Create/resize/destroy platform windows to match each active viewport.
14567
    // Skip the main viewport (index 0), which is always fully handled by the application!
14568
0
    for (int i = 1; i < g.Viewports.Size; i++)
14569
0
    {
14570
0
        ImGuiViewportP* viewport = g.Viewports[i];
14571
14572
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
14573
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
14574
0
        bool destroy_platform_window = false;
14575
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
14576
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
14577
0
        if (destroy_platform_window)
14578
0
        {
14579
0
            DestroyPlatformWindow(viewport);
14580
0
            continue;
14581
0
        }
14582
14583
        // New windows that appears directly in a new viewport won't always have a size on their first frame
14584
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
14585
0
            continue;
14586
14587
        // Create window
14588
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
14589
0
        if (is_new_platform_window)
14590
0
        {
14591
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14592
0
            g.PlatformIO.Platform_CreateWindow(viewport);
14593
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
14594
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
14595
0
            viewport->LastNameHash = 0;
14596
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
14597
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
14598
0
            viewport->PlatformWindowCreated = true;
14599
0
        }
14600
14601
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
14602
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
14603
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
14604
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
14605
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
14606
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
14607
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
14608
0
        viewport->LastPlatformPos = viewport->Pos;
14609
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
14610
14611
        // Update title bar (if it changed)
14612
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
14613
0
        {
14614
0
            const char* title_begin = window_for_title->Name;
14615
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
14616
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
14617
0
            if (viewport->LastNameHash != title_hash)
14618
0
            {
14619
0
                char title_end_backup_c = *title_end;
14620
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
14621
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
14622
0
                *title_end = title_end_backup_c;
14623
0
                viewport->LastNameHash = title_hash;
14624
0
            }
14625
0
        }
14626
14627
        // Update alpha (if it changed)
14628
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
14629
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
14630
0
        viewport->LastAlpha = viewport->Alpha;
14631
14632
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
14633
0
        if (g.PlatformIO.Platform_UpdateWindow)
14634
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
14635
14636
0
        if (is_new_platform_window)
14637
0
        {
14638
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
14639
0
            if (g.FrameCount < 3)
14640
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14641
14642
            // Show window
14643
0
            g.PlatformIO.Platform_ShowWindow(viewport);
14644
14645
            // Even without focus, we assume the window becomes front-most.
14646
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
14647
0
            if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
14648
0
                viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
14649
0
        }
14650
14651
        // Clear request flags
14652
0
        viewport->ClearRequestFlags();
14653
0
    }
14654
0
}
14655
14656
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
14657
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
14658
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
14659
//
14660
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14661
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14662
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14663
//            MyRenderFunction(platform_io.Viewports[i], my_args);
14664
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14665
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14666
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
14667
//
14668
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
14669
0
{
14670
    // Skip the main viewport (index 0), which is always fully handled by the application!
14671
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14672
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14673
0
    {
14674
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
14675
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
14676
0
            continue;
14677
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
14678
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
14679
0
    }
14680
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14681
0
    {
14682
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
14683
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
14684
0
            continue;
14685
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
14686
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
14687
0
    }
14688
0
}
14689
14690
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
14691
0
{
14692
0
    ImGuiContext& g = *GImGui;
14693
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
14694
0
    {
14695
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14696
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
14697
0
            return monitor_n;
14698
0
    }
14699
0
    return -1;
14700
0
}
14701
14702
// Search for the monitor with the largest intersection area with the given rectangle
14703
// We generally try to avoid searching loops but the monitor count should be very small here
14704
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
14705
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
14706
35.9k
{
14707
35.9k
    ImGuiContext& g = *GImGui;
14708
14709
35.9k
    const int monitor_count = g.PlatformIO.Monitors.Size;
14710
35.9k
    if (monitor_count <= 1)
14711
35.9k
        return monitor_count - 1;
14712
14713
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
14714
    // This is necessary for tooltips which always resize down to zero at first.
14715
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
14716
0
    int best_monitor_n = -1;
14717
0
    float best_monitor_surface = 0.001f;
14718
14719
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
14720
0
    {
14721
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14722
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
14723
0
        if (monitor_rect.Contains(rect))
14724
0
            return monitor_n;
14725
0
        ImRect overlapping_rect = rect;
14726
0
        overlapping_rect.ClipWithFull(monitor_rect);
14727
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
14728
0
        if (overlapping_surface < best_monitor_surface)
14729
0
            continue;
14730
0
        best_monitor_surface = overlapping_surface;
14731
0
        best_monitor_n = monitor_n;
14732
0
    }
14733
0
    return best_monitor_n;
14734
0
}
14735
14736
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
14737
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
14738
35.9k
{
14739
35.9k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
14740
35.9k
}
14741
14742
// Return value is always != NULL, but don't hold on it across frames.
14743
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
14744
0
{
14745
0
    ImGuiContext& g = *GImGui;
14746
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
14747
0
    int monitor_idx = viewport->PlatformMonitor;
14748
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
14749
0
        return &g.PlatformIO.Monitors[monitor_idx];
14750
0
    return &g.FallbackMonitor;
14751
0
}
14752
14753
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
14754
0
{
14755
0
    ImGuiContext& g = *GImGui;
14756
0
    if (viewport->PlatformWindowCreated)
14757
0
    {
14758
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14759
0
        if (g.PlatformIO.Renderer_DestroyWindow)
14760
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
14761
0
        if (g.PlatformIO.Platform_DestroyWindow)
14762
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
14763
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
14764
14765
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
14766
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
14767
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
14768
0
            viewport->PlatformWindowCreated = false;
14769
0
    }
14770
0
    else
14771
0
    {
14772
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
14773
0
    }
14774
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
14775
0
    viewport->ClearRequestFlags();
14776
0
}
14777
14778
void ImGui::DestroyPlatformWindows()
14779
0
{
14780
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
14781
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
14782
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
14783
    // code to operator a consistent manner.
14784
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
14785
    // crashing if it doesn't have data stored.
14786
0
    ImGuiContext& g = *GImGui;
14787
0
    for (int i = 0; i < g.Viewports.Size; i++)
14788
0
        DestroyPlatformWindow(g.Viewports[i]);
14789
0
}
14790
14791
14792
//-----------------------------------------------------------------------------
14793
// [SECTION] DOCKING
14794
//-----------------------------------------------------------------------------
14795
// Docking: Internal Types
14796
// Docking: Forward Declarations
14797
// Docking: ImGuiDockContext
14798
// Docking: ImGuiDockContext Docking/Undocking functions
14799
// Docking: ImGuiDockNode
14800
// Docking: ImGuiDockNode Tree manipulation functions
14801
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
14802
// Docking: Builder Functions
14803
// Docking: Begin/End Support Functions (called from Begin/End)
14804
// Docking: Settings
14805
//-----------------------------------------------------------------------------
14806
14807
//-----------------------------------------------------------------------------
14808
// Typical Docking call flow: (root level is generally public API):
14809
//-----------------------------------------------------------------------------
14810
// - NewFrame()                               new dear imgui frame
14811
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
14812
//    | - DockContextProcessUndockWindow()    - process one window undocking request
14813
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
14814
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
14815
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
14816
//    | - DockContextProcessDock()            - process one docking request
14817
//    | - DockNodeUpdate()
14818
//    |   - DockNodeUpdateForRootNode()
14819
//    |     - DockNodeUpdateFlagsAndCollapse()
14820
//    |     - DockNodeFindInfo()
14821
//    |   - destroy unused node or tab bar
14822
//    |   - create dock node host window
14823
//    |      - Begin() etc.
14824
//    |   - DockNodeStartMouseMovingWindow()
14825
//    |   - DockNodeTreeUpdatePosSize()
14826
//    |   - DockNodeTreeUpdateSplitter()
14827
//    |   - draw node background
14828
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
14829
//    |     - DockNodeAddTabBar()
14830
//    |     - DockNodeUpdateWindowMenu()
14831
//    |     - DockNodeCalcTabBarLayout()
14832
//    |     - BeginTabBarEx()
14833
//    |     - TabItemEx() calls
14834
//    |     - EndTabBar()
14835
//    |   - BeginDockableDragDropTarget()
14836
//    |      - DockNodeUpdate()               - recurse into child nodes...
14837
//-----------------------------------------------------------------------------
14838
// - DockSpace()                              user submit a dockspace into a window
14839
//    | Begin(Child)                          - create a child window
14840
//    | DockNodeUpdate()                      - call main dock node update function
14841
//    | End(Child)
14842
//    | ItemSize()
14843
//-----------------------------------------------------------------------------
14844
// - Begin()
14845
//    | BeginDocked()
14846
//    | BeginDockableDragDropSource()
14847
//    | BeginDockableDragDropTarget()
14848
//    | - DockNodePreviewDockRender()
14849
//-----------------------------------------------------------------------------
14850
// - EndFrame()
14851
//    | DockContextEndFrame()
14852
//-----------------------------------------------------------------------------
14853
14854
//-----------------------------------------------------------------------------
14855
// Docking: Internal Types
14856
//-----------------------------------------------------------------------------
14857
// - ImGuiDockRequestType
14858
// - ImGuiDockRequest
14859
// - ImGuiDockPreviewData
14860
// - ImGuiDockNodeSettings
14861
// - ImGuiDockContext
14862
//-----------------------------------------------------------------------------
14863
14864
enum ImGuiDockRequestType
14865
{
14866
    ImGuiDockRequestType_None = 0,
14867
    ImGuiDockRequestType_Dock,
14868
    ImGuiDockRequestType_Undock,
14869
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
14870
};
14871
14872
struct ImGuiDockRequest
14873
{
14874
    ImGuiDockRequestType    Type;
14875
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
14876
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
14877
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
14878
    ImGuiDir                DockSplitDir;
14879
    float                   DockSplitRatio;
14880
    bool                    DockSplitOuter;
14881
    ImGuiWindow*            UndockTargetWindow;
14882
    ImGuiDockNode*          UndockTargetNode;
14883
14884
    ImGuiDockRequest()
14885
0
    {
14886
0
        Type = ImGuiDockRequestType_None;
14887
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
14888
0
        DockTargetNode = UndockTargetNode = NULL;
14889
0
        DockSplitDir = ImGuiDir_None;
14890
0
        DockSplitRatio = 0.5f;
14891
0
        DockSplitOuter = false;
14892
0
    }
14893
};
14894
14895
struct ImGuiDockPreviewData
14896
{
14897
    ImGuiDockNode   FutureNode;
14898
    bool            IsDropAllowed;
14899
    bool            IsCenterAvailable;
14900
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
14901
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
14902
    ImGuiDockNode*  SplitNode;
14903
    ImGuiDir        SplitDir;
14904
    float           SplitRatio;
14905
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
14906
14907
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
14908
};
14909
14910
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
14911
struct ImGuiDockNodeSettings
14912
{
14913
    ImGuiID             ID;
14914
    ImGuiID             ParentNodeId;
14915
    ImGuiID             ParentWindowId;
14916
    ImGuiID             SelectedTabId;
14917
    signed char         SplitAxis;
14918
    char                Depth;
14919
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
14920
    ImVec2ih            Pos;
14921
    ImVec2ih            Size;
14922
    ImVec2ih            SizeRef;
14923
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
14924
};
14925
14926
//-----------------------------------------------------------------------------
14927
// Docking: Forward Declarations
14928
//-----------------------------------------------------------------------------
14929
14930
namespace ImGui
14931
{
14932
    // ImGuiDockContext
14933
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
14934
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
14935
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
14936
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
14937
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
14938
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
14939
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
14940
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
14941
14942
    // ImGuiDockNode
14943
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
14944
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
14945
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
14946
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
14947
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
14948
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
14949
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
14950
    static void             DockNodeUpdate(ImGuiDockNode* node);
14951
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
14952
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
14953
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
14954
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
14955
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
14956
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
14957
    static void             DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
14958
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
14959
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
14960
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
14961
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
14962
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
14963
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
14964
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
14965
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
14966
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
14967
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
14968
14969
    // ImGuiDockNode tree manipulations
14970
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
14971
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
14972
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
14973
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
14974
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
14975
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
14976
14977
    // Settings
14978
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
14979
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
14980
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
14981
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
14982
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
14983
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
14984
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
14985
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
14986
}
14987
14988
//-----------------------------------------------------------------------------
14989
// Docking: ImGuiDockContext
14990
//-----------------------------------------------------------------------------
14991
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
14992
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
14993
// At boot time only, we run a simple GC to remove nodes that have no references.
14994
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
14995
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
14996
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
14997
//-----------------------------------------------------------------------------
14998
// - DockContextInitialize()
14999
// - DockContextShutdown()
15000
// - DockContextClearNodes()
15001
// - DockContextRebuildNodes()
15002
// - DockContextNewFrameUpdateUndocking()
15003
// - DockContextNewFrameUpdateDocking()
15004
// - DockContextEndFrame()
15005
// - DockContextFindNodeByID()
15006
// - DockContextBindNodeToWindow()
15007
// - DockContextGenNodeID()
15008
// - DockContextAddNode()
15009
// - DockContextRemoveNode()
15010
// - ImGuiDockContextPruneNodeData
15011
// - DockContextPruneUnusedSettingsNodes()
15012
// - DockContextBuildNodesFromSettings()
15013
// - DockContextBuildAddWindowsToNodes()
15014
//-----------------------------------------------------------------------------
15015
15016
void ImGui::DockContextInitialize(ImGuiContext* ctx)
15017
1
{
15018
1
    ImGuiContext& g = *ctx;
15019
15020
    // Add .ini handle for persistent docking data
15021
1
    ImGuiSettingsHandler ini_handler;
15022
1
    ini_handler.TypeName = "Docking";
15023
1
    ini_handler.TypeHash = ImHashStr("Docking");
15024
1
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
15025
1
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
15026
1
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
15027
1
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
15028
1
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
15029
1
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
15030
1
    g.SettingsHandlers.push_back(ini_handler);
15031
15032
1
    g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
15033
1
}
15034
15035
void ImGui::DockContextShutdown(ImGuiContext* ctx)
15036
0
{
15037
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15038
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15039
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15040
0
            IM_DELETE(node);
15041
0
}
15042
15043
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
15044
0
{
15045
0
    IM_UNUSED(ctx);
15046
0
    IM_ASSERT(ctx == GImGui);
15047
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
15048
0
    DockBuilderRemoveNodeChildNodes(root_id);
15049
0
}
15050
15051
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
15052
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
15053
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
15054
0
{
15055
0
    ImGuiContext& g = *ctx;
15056
0
    ImGuiDockContext* dc = &ctx->DockContext;
15057
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
15058
0
    SaveIniSettingsToMemory();
15059
0
    ImGuiID root_id = 0; // Rebuild all
15060
0
    DockContextClearNodes(ctx, root_id, false);
15061
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
15062
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
15063
0
}
15064
15065
// Docking context update function, called by NewFrame()
15066
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
15067
35.9k
{
15068
35.9k
    ImGuiContext& g = *ctx;
15069
35.9k
    ImGuiDockContext* dc = &ctx->DockContext;
15070
35.9k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15071
0
    {
15072
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
15073
0
            DockContextClearNodes(ctx, 0, true);
15074
0
        return;
15075
0
    }
15076
15077
    // Setting NoSplit at runtime merges all nodes
15078
35.9k
    if (g.IO.ConfigDockingNoSplit)
15079
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
15080
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15081
0
                if (node->IsRootNode() && node->IsSplitNode())
15082
0
                {
15083
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
15084
                    //dc->WantFullRebuild = true;
15085
0
                }
15086
15087
    // Process full rebuild
15088
#if 0
15089
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
15090
        dc->WantFullRebuild = true;
15091
#endif
15092
35.9k
    if (dc->WantFullRebuild)
15093
0
    {
15094
0
        DockContextRebuildNodes(ctx);
15095
0
        dc->WantFullRebuild = false;
15096
0
    }
15097
15098
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
15099
35.9k
    for (int n = 0; n < dc->Requests.Size; n++)
15100
0
    {
15101
0
        ImGuiDockRequest* req = &dc->Requests[n];
15102
0
        if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetWindow)
15103
0
            DockContextProcessUndockWindow(ctx, req->UndockTargetWindow);
15104
0
        else if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetNode)
15105
0
            DockContextProcessUndockNode(ctx, req->UndockTargetNode);
15106
0
    }
15107
35.9k
}
15108
15109
// Docking context update function, called by NewFrame()
15110
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
15111
35.9k
{
15112
35.9k
    ImGuiContext& g = *ctx;
15113
35.9k
    ImGuiDockContext* dc  = &ctx->DockContext;
15114
35.9k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15115
0
        return;
15116
15117
    // [DEBUG] Store hovered dock node.
15118
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
15119
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
15120
35.9k
    g.DebugHoveredDockNode = NULL;
15121
35.9k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
15122
823
    {
15123
823
        if (hovered_window->DockNodeAsHost)
15124
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
15125
823
        else if (hovered_window->RootWindow->DockNode)
15126
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
15127
823
    }
15128
15129
    // Process Docking requests
15130
35.9k
    for (int n = 0; n < dc->Requests.Size; n++)
15131
0
        if (dc->Requests[n].Type == ImGuiDockRequestType_Dock)
15132
0
            DockContextProcessDock(ctx, &dc->Requests[n]);
15133
35.9k
    dc->Requests.resize(0);
15134
15135
    // Create windows for each automatic docking nodes
15136
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
15137
35.9k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15138
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15139
0
            if (node->IsFloatingNode())
15140
0
                DockNodeUpdate(node);
15141
35.9k
}
15142
15143
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
15144
35.9k
{
15145
    // Draw backgrounds of node missing their window
15146
35.9k
    ImGuiContext& g = *ctx;
15147
35.9k
    ImGuiDockContext* dc = &g.DockContext;
15148
35.9k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15149
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15150
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
15151
0
            {
15152
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
15153
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), DOCKING_SPLITTER_SIZE);
15154
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
15155
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
15156
0
            }
15157
35.9k
}
15158
15159
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
15160
0
{
15161
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
15162
0
}
15163
15164
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
15165
0
{
15166
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
15167
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
15168
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
15169
0
    ImGuiID id = 0x0001;
15170
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
15171
0
        id++;
15172
0
    return id;
15173
0
}
15174
15175
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
15176
0
{
15177
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
15178
0
    ImGuiContext& g = *ctx;
15179
0
    if (id == 0)
15180
0
        id = DockContextGenNodeID(ctx);
15181
0
    else
15182
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
15183
15184
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
15185
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
15186
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
15187
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
15188
0
    return node;
15189
0
}
15190
15191
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
15192
0
{
15193
0
    ImGuiContext& g = *ctx;
15194
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15195
15196
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
15197
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
15198
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
15199
0
    IM_ASSERT(node->Windows.Size == 0);
15200
15201
0
    if (node->HostWindow)
15202
0
        node->HostWindow->DockNodeAsHost = NULL;
15203
15204
0
    ImGuiDockNode* parent_node = node->ParentNode;
15205
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
15206
0
    if (merge)
15207
0
    {
15208
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
15209
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
15210
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
15211
0
    }
15212
0
    else
15213
0
    {
15214
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
15215
0
            if (parent_node->ChildNodes[n] == node)
15216
0
                node->ParentNode->ChildNodes[n] = NULL;
15217
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
15218
0
        IM_DELETE(node);
15219
0
    }
15220
0
}
15221
15222
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
15223
0
{
15224
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
15225
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
15226
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
15227
0
}
15228
15229
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
15230
struct ImGuiDockContextPruneNodeData
15231
{
15232
    int         CountWindows, CountChildWindows, CountChildNodes;
15233
    ImGuiID     RootId;
15234
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
15235
};
15236
15237
// Garbage collect unused nodes (run once at init time)
15238
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
15239
0
{
15240
0
    ImGuiContext& g = *ctx;
15241
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15242
0
    IM_ASSERT(g.Windows.Size == 0);
15243
15244
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
15245
0
    pool.Reserve(dc->NodesSettings.Size);
15246
15247
    // Count child nodes and compute RootID
15248
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15249
0
    {
15250
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15251
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
15252
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
15253
0
        if (settings->ParentNodeId)
15254
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
15255
0
    }
15256
15257
    // Count reference to dock ids from dockspaces
15258
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
15259
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15260
0
    {
15261
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15262
0
        if (settings->ParentWindowId != 0)
15263
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
15264
0
                if (window_settings->DockId)
15265
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
15266
0
                        data->CountChildNodes++;
15267
0
    }
15268
15269
    // Count reference to dock ids from window settings
15270
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
15271
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
15272
0
        if (ImGuiID dock_id = settings->DockId)
15273
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
15274
0
            {
15275
0
                data->CountWindows++;
15276
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
15277
0
                    data_root->CountChildWindows++;
15278
0
            }
15279
15280
    // Prune
15281
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15282
0
    {
15283
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15284
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
15285
0
        if (data->CountWindows > 1)
15286
0
            continue;
15287
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
15288
15289
0
        bool remove = false;
15290
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
15291
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
15292
0
        remove |= (data_root->CountChildWindows == 0);
15293
0
        if (remove)
15294
0
        {
15295
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
15296
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
15297
0
            settings->ID = 0;
15298
0
        }
15299
0
    }
15300
0
}
15301
15302
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
15303
0
{
15304
    // Build nodes
15305
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
15306
0
    {
15307
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
15308
0
        if (settings->ID == 0)
15309
0
            continue;
15310
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
15311
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
15312
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
15313
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
15314
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
15315
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
15316
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
15317
0
            node->ParentNode->ChildNodes[0] = node;
15318
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
15319
0
            node->ParentNode->ChildNodes[1] = node;
15320
0
        node->SelectedTabId = settings->SelectedTabId;
15321
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
15322
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
15323
15324
        // Bind host window immediately if it already exist (in case of a rebuild)
15325
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
15326
0
        char host_window_title[20];
15327
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
15328
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
15329
0
    }
15330
0
}
15331
15332
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
15333
0
{
15334
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
15335
0
    ImGuiContext& g = *ctx;
15336
0
    for (int n = 0; n < g.Windows.Size; n++)
15337
0
    {
15338
0
        ImGuiWindow* window = g.Windows[n];
15339
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
15340
0
            continue;
15341
0
        if (window->DockNode != NULL)
15342
0
            continue;
15343
15344
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
15345
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
15346
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
15347
0
            DockNodeAddWindow(node, window, true);
15348
0
    }
15349
0
}
15350
15351
//-----------------------------------------------------------------------------
15352
// Docking: ImGuiDockContext Docking/Undocking functions
15353
//-----------------------------------------------------------------------------
15354
// - DockContextQueueDock()
15355
// - DockContextQueueUndockWindow()
15356
// - DockContextQueueUndockNode()
15357
// - DockContextQueueNotifyRemovedNode()
15358
// - DockContextProcessDock()
15359
// - DockContextProcessUndockWindow()
15360
// - DockContextProcessUndockNode()
15361
// - DockContextCalcDropPosForDocking()
15362
//-----------------------------------------------------------------------------
15363
15364
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
15365
0
{
15366
0
    IM_ASSERT(target != payload);
15367
0
    ImGuiDockRequest req;
15368
0
    req.Type = ImGuiDockRequestType_Dock;
15369
0
    req.DockTargetWindow = target;
15370
0
    req.DockTargetNode = target_node;
15371
0
    req.DockPayload = payload;
15372
0
    req.DockSplitDir = split_dir;
15373
0
    req.DockSplitRatio = split_ratio;
15374
0
    req.DockSplitOuter = split_outer;
15375
0
    ctx->DockContext.Requests.push_back(req);
15376
0
}
15377
15378
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
15379
0
{
15380
0
    ImGuiDockRequest req;
15381
0
    req.Type = ImGuiDockRequestType_Undock;
15382
0
    req.UndockTargetWindow = window;
15383
0
    ctx->DockContext.Requests.push_back(req);
15384
0
}
15385
15386
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15387
0
{
15388
0
    ImGuiDockRequest req;
15389
0
    req.Type = ImGuiDockRequestType_Undock;
15390
0
    req.UndockTargetNode = node;
15391
0
    ctx->DockContext.Requests.push_back(req);
15392
0
}
15393
15394
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
15395
0
{
15396
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15397
0
    for (int n = 0; n < dc->Requests.Size; n++)
15398
0
        if (dc->Requests[n].DockTargetNode == node)
15399
0
            dc->Requests[n].Type = ImGuiDockRequestType_None;
15400
0
}
15401
15402
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
15403
0
{
15404
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
15405
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
15406
15407
0
    ImGuiContext& g = *ctx;
15408
0
    IM_UNUSED(g);
15409
15410
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
15411
0
    ImGuiWindow* target_window = req->DockTargetWindow;
15412
0
    ImGuiDockNode* node = req->DockTargetNode;
15413
0
    if (payload_window)
15414
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
15415
0
    else
15416
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
15417
15418
    // Decide which Tab will be selected at the end of the operation
15419
0
    ImGuiID next_selected_id = 0;
15420
0
    ImGuiDockNode* payload_node = NULL;
15421
0
    if (payload_window)
15422
0
    {
15423
0
        payload_node = payload_window->DockNodeAsHost;
15424
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
15425
0
        if (payload_node && payload_node->IsLeafNode())
15426
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
15427
0
        if (payload_node == NULL)
15428
0
            next_selected_id = payload_window->TabId;
15429
0
    }
15430
15431
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
15432
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
15433
0
    if (node)
15434
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
15435
0
    if (node && target_window && node == target_window->DockNodeAsHost)
15436
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
15437
15438
    // Create new node and add existing window to it
15439
0
    if (node == NULL)
15440
0
    {
15441
0
        node = DockContextAddNode(ctx, 0);
15442
0
        node->Pos = target_window->Pos;
15443
0
        node->Size = target_window->Size;
15444
0
        if (target_window->DockNodeAsHost == NULL)
15445
0
        {
15446
0
            DockNodeAddWindow(node, target_window, true);
15447
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
15448
0
            target_window->DockIsActive = true;
15449
0
        }
15450
0
    }
15451
15452
0
    ImGuiDir split_dir = req->DockSplitDir;
15453
0
    if (split_dir != ImGuiDir_None)
15454
0
    {
15455
        // Split into two, one side will be our payload node unless we are dropping a loose window
15456
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
15457
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
15458
0
        const float split_ratio = req->DockSplitRatio;
15459
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
15460
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
15461
0
        new_node->HostWindow = node->HostWindow;
15462
0
        node = new_node;
15463
0
    }
15464
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15465
15466
0
    if (node != payload_node)
15467
0
    {
15468
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
15469
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
15470
0
        {
15471
0
            DockNodeAddTabBar(node);
15472
0
            for (int n = 0; n < node->Windows.Size; n++)
15473
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15474
0
        }
15475
15476
0
        if (payload_node != NULL)
15477
0
        {
15478
            // Transfer full payload node (with 1+ child windows or child nodes)
15479
0
            if (payload_node->IsSplitNode())
15480
0
            {
15481
0
                if (node->Windows.Size > 0)
15482
0
                {
15483
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
15484
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
15485
                    // This allows us to preserve some of the underlying dock tree settings nicely.
15486
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
15487
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
15488
0
                    if (visible_node->TabBar)
15489
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
15490
0
                    DockNodeMoveWindows(node, visible_node);
15491
0
                    DockNodeMoveWindows(visible_node, node);
15492
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
15493
0
                }
15494
0
                if (node->IsCentralNode())
15495
0
                {
15496
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
15497
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
15498
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
15499
0
                    IM_ASSERT(last_focused_node != NULL);
15500
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
15501
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
15502
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
15503
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
15504
0
                    last_focused_root_node->CentralNode = last_focused_node;
15505
0
                }
15506
15507
0
                IM_ASSERT(node->Windows.Size == 0);
15508
0
                DockNodeMoveChildNodes(node, payload_node);
15509
0
            }
15510
0
            else
15511
0
            {
15512
0
                const ImGuiID payload_dock_id = payload_node->ID;
15513
0
                DockNodeMoveWindows(node, payload_node);
15514
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15515
0
            }
15516
0
            DockContextRemoveNode(ctx, payload_node, true);
15517
0
        }
15518
0
        else if (payload_window)
15519
0
        {
15520
            // Transfer single window
15521
0
            const ImGuiID payload_dock_id = payload_window->DockId;
15522
0
            node->VisibleWindow = payload_window;
15523
0
            DockNodeAddWindow(node, payload_window, true);
15524
0
            if (payload_dock_id != 0)
15525
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15526
0
        }
15527
0
    }
15528
0
    else
15529
0
    {
15530
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
15531
0
        node->WantHiddenTabBarUpdate = true;
15532
0
    }
15533
15534
    // Update selection immediately
15535
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
15536
0
        tab_bar->NextSelectedTabId = next_selected_id;
15537
0
    MarkIniSettingsDirty();
15538
0
}
15539
15540
// Problem:
15541
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
15542
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
15543
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
15544
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
15545
// Solution:
15546
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
15547
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
15548
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
15549
0
{
15550
0
    if (ref_viewport == NULL)
15551
0
        return size;
15552
15553
0
    ImGuiContext& g = *GImGui;
15554
0
    ImVec2 max_size = ImFloor(ref_viewport->WorkSize * 0.90f);
15555
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
15556
0
    {
15557
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
15558
0
        max_size = ImFloor(monitor->WorkSize * 0.90f);
15559
0
    }
15560
0
    return ImMin(size, max_size);
15561
0
}
15562
15563
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
15564
0
{
15565
0
    ImGuiContext& g = *ctx;
15566
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
15567
0
    if (window->DockNode)
15568
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
15569
0
    else
15570
0
        window->DockId = 0;
15571
0
    window->Collapsed = false;
15572
0
    window->DockIsActive = false;
15573
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
15574
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
15575
15576
0
    MarkIniSettingsDirty();
15577
0
}
15578
15579
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15580
0
{
15581
0
    ImGuiContext& g = *ctx;
15582
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
15583
0
    IM_ASSERT(node->IsLeafNode());
15584
0
    IM_ASSERT(node->Windows.Size >= 1);
15585
15586
0
    if (node->IsRootNode() || node->IsCentralNode())
15587
0
    {
15588
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
15589
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
15590
0
        new_node->Pos = node->Pos;
15591
0
        new_node->Size = node->Size;
15592
0
        new_node->SizeRef = node->SizeRef;
15593
0
        DockNodeMoveWindows(new_node, node);
15594
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
15595
0
        node = new_node;
15596
0
    }
15597
0
    else
15598
0
    {
15599
        // Otherwise extract our node and merge our sibling back into the parent node.
15600
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15601
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
15602
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
15603
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
15604
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
15605
0
        node->ParentNode = NULL;
15606
0
    }
15607
0
    for (int n = 0; n < node->Windows.Size; n++)
15608
0
    {
15609
0
        ImGuiWindow* window = node->Windows[n];
15610
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15611
0
        if (window->ParentWindow)
15612
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
15613
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
15614
0
    }
15615
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
15616
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
15617
0
    node->WantMouseMove = true;
15618
0
    MarkIniSettingsDirty();
15619
0
}
15620
15621
// This is mostly used for automation.
15622
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
15623
0
{
15624
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
15625
    // (which would be functionally identical) we only show the outer one. Reflect this here.
15626
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
15627
0
        split_outer = true;
15628
0
    ImGuiDockPreviewData split_data;
15629
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
15630
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
15631
0
        return false;
15632
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
15633
0
    return true;
15634
0
}
15635
15636
//-----------------------------------------------------------------------------
15637
// Docking: ImGuiDockNode
15638
//-----------------------------------------------------------------------------
15639
// - DockNodeGetTabOrder()
15640
// - DockNodeAddWindow()
15641
// - DockNodeRemoveWindow()
15642
// - DockNodeMoveChildNodes()
15643
// - DockNodeMoveWindows()
15644
// - DockNodeApplyPosSizeToWindows()
15645
// - DockNodeHideHostWindow()
15646
// - ImGuiDockNodeFindInfoResults
15647
// - DockNodeFindInfo()
15648
// - DockNodeFindWindowByID()
15649
// - DockNodeUpdateFlagsAndCollapse()
15650
// - DockNodeUpdateHasCentralNodeFlag()
15651
// - DockNodeUpdateVisibleFlag()
15652
// - DockNodeStartMouseMovingWindow()
15653
// - DockNodeUpdate()
15654
// - DockNodeUpdateWindowMenu()
15655
// - DockNodeBeginAmendTabBar()
15656
// - DockNodeEndAmendTabBar()
15657
// - DockNodeUpdateTabBar()
15658
// - DockNodeAddTabBar()
15659
// - DockNodeRemoveTabBar()
15660
// - DockNodeIsDropAllowedOne()
15661
// - DockNodeIsDropAllowed()
15662
// - DockNodeCalcTabBarLayout()
15663
// - DockNodeCalcSplitRects()
15664
// - DockNodeCalcDropRectsAndTestMousePos()
15665
// - DockNodePreviewDockSetup()
15666
// - DockNodePreviewDockRender()
15667
//-----------------------------------------------------------------------------
15668
15669
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
15670
0
{
15671
0
    ID = id;
15672
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
15673
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
15674
0
    TabBar = NULL;
15675
0
    SplitAxis = ImGuiAxis_None;
15676
15677
0
    State = ImGuiDockNodeState_Unknown;
15678
0
    LastBgColor = IM_COL32_WHITE;
15679
0
    HostWindow = VisibleWindow = NULL;
15680
0
    CentralNode = OnlyNodeWithWindows = NULL;
15681
0
    CountNodeWithWindows = 0;
15682
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
15683
0
    LastFocusedNodeId = 0;
15684
0
    SelectedTabId = 0;
15685
0
    WantCloseTabId = 0;
15686
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
15687
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
15688
0
    IsVisible = true;
15689
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
15690
0
    IsBgDrawnThisFrame = false;
15691
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
15692
0
}
15693
15694
ImGuiDockNode::~ImGuiDockNode()
15695
0
{
15696
0
    IM_DELETE(TabBar);
15697
0
    TabBar = NULL;
15698
0
    ChildNodes[0] = ChildNodes[1] = NULL;
15699
0
}
15700
15701
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
15702
0
{
15703
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
15704
0
    if (tab_bar == NULL)
15705
0
        return -1;
15706
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
15707
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
15708
0
}
15709
15710
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
15711
0
{
15712
0
    window->Hidden = true;
15713
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
15714
0
}
15715
15716
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
15717
0
{
15718
0
    ImGuiContext& g = *GImGui; (void)g;
15719
0
    if (window->DockNode)
15720
0
    {
15721
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
15722
0
        IM_ASSERT(window->DockNode->ID != node->ID);
15723
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
15724
0
    }
15725
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
15726
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15727
15728
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
15729
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
15730
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
15731
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
15732
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
15733
15734
0
    node->Windows.push_back(window);
15735
0
    node->WantHiddenTabBarUpdate = true;
15736
0
    window->DockNode = node;
15737
0
    window->DockId = node->ID;
15738
0
    window->DockIsActive = (node->Windows.Size > 1);
15739
0
    window->DockTabWantClose = false;
15740
15741
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
15742
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
15743
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
15744
0
    {
15745
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
15746
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
15747
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
15748
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
15749
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
15750
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
15751
0
    }
15752
15753
    // Add to tab bar if requested
15754
0
    if (add_to_tab_bar)
15755
0
    {
15756
0
        if (node->TabBar == NULL)
15757
0
        {
15758
0
            DockNodeAddTabBar(node);
15759
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
15760
15761
            // Add existing windows
15762
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
15763
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15764
0
        }
15765
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
15766
0
    }
15767
15768
0
    DockNodeUpdateVisibleFlag(node);
15769
15770
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
15771
0
    if (node->HostWindow)
15772
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
15773
0
}
15774
15775
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
15776
0
{
15777
0
    ImGuiContext& g = *GImGui;
15778
0
    IM_ASSERT(window->DockNode == node);
15779
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
15780
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
15781
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
15782
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15783
15784
0
    window->DockNode = NULL;
15785
0
    window->DockIsActive = window->DockTabWantClose = false;
15786
0
    window->DockId = save_dock_id;
15787
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15788
0
    if (window->ParentWindow)
15789
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
15790
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
15791
15792
    // Remove window
15793
0
    bool erased = false;
15794
0
    for (int n = 0; n < node->Windows.Size; n++)
15795
0
        if (node->Windows[n] == window)
15796
0
        {
15797
0
            node->Windows.erase(node->Windows.Data + n);
15798
0
            erased = true;
15799
0
            break;
15800
0
        }
15801
0
    if (!erased)
15802
0
        IM_ASSERT(erased);
15803
0
    if (node->VisibleWindow == window)
15804
0
        node->VisibleWindow = NULL;
15805
15806
    // Remove tab and possibly tab bar
15807
0
    node->WantHiddenTabBarUpdate = true;
15808
0
    if (node->TabBar)
15809
0
    {
15810
0
        TabBarRemoveTab(node->TabBar, window->TabId);
15811
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
15812
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
15813
0
            DockNodeRemoveTabBar(node);
15814
0
    }
15815
15816
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
15817
0
    {
15818
        // Automatic dock node delete themselves if they are not holding at least one tab
15819
0
        DockContextRemoveNode(&g, node, true);
15820
0
        return;
15821
0
    }
15822
15823
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
15824
0
    {
15825
0
        ImGuiWindow* remaining_window = node->Windows[0];
15826
0
        if (node->HostWindow->ViewportOwned && node->IsRootNode())
15827
0
        {
15828
            // Transfer viewport back to the remaining loose window
15829
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X=>%08X for Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, remaining_window->ID, remaining_window->Name);
15830
0
            IM_ASSERT(node->HostWindow->Viewport->Window == node->HostWindow);
15831
0
            node->HostWindow->Viewport->Window = remaining_window;
15832
0
            node->HostWindow->Viewport->ID = remaining_window->ID;
15833
0
        }
15834
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
15835
0
    }
15836
15837
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
15838
0
    DockNodeUpdateVisibleFlag(node);
15839
0
}
15840
15841
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
15842
0
{
15843
0
    IM_ASSERT(dst_node->Windows.Size == 0);
15844
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
15845
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
15846
0
    if (dst_node->ChildNodes[0])
15847
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
15848
0
    if (dst_node->ChildNodes[1])
15849
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
15850
0
    dst_node->SplitAxis = src_node->SplitAxis;
15851
0
    dst_node->SizeRef = src_node->SizeRef;
15852
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
15853
0
}
15854
15855
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
15856
0
{
15857
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
15858
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
15859
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
15860
0
    if (src_tab_bar != NULL)
15861
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
15862
15863
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
15864
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
15865
0
    if (move_tab_bar)
15866
0
    {
15867
0
        dst_node->TabBar = src_node->TabBar;
15868
0
        src_node->TabBar = NULL;
15869
0
    }
15870
15871
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
15872
0
    for (ImGuiWindow* window : src_node->Windows)
15873
0
    {
15874
0
        window->DockNode = NULL;
15875
0
        window->DockIsActive = false;
15876
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
15877
0
    }
15878
0
    src_node->Windows.clear();
15879
15880
0
    if (!move_tab_bar && src_node->TabBar)
15881
0
    {
15882
0
        if (dst_node->TabBar)
15883
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
15884
0
        DockNodeRemoveTabBar(src_node);
15885
0
    }
15886
0
}
15887
15888
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
15889
0
{
15890
0
    for (int n = 0; n < node->Windows.Size; n++)
15891
0
    {
15892
0
        SetWindowPos(node->Windows[n], node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
15893
0
        SetWindowSize(node->Windows[n], node->Size, ImGuiCond_Always);
15894
0
    }
15895
0
}
15896
15897
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
15898
0
{
15899
0
    if (node->HostWindow)
15900
0
    {
15901
0
        if (node->HostWindow->DockNodeAsHost == node)
15902
0
            node->HostWindow->DockNodeAsHost = NULL;
15903
0
        node->HostWindow = NULL;
15904
0
    }
15905
15906
0
    if (node->Windows.Size == 1)
15907
0
    {
15908
0
        node->VisibleWindow = node->Windows[0];
15909
0
        node->Windows[0]->DockIsActive = false;
15910
0
    }
15911
15912
0
    if (node->TabBar)
15913
0
        DockNodeRemoveTabBar(node);
15914
0
}
15915
15916
// Search function called once by root node in DockNodeUpdate()
15917
struct ImGuiDockNodeTreeInfo
15918
{
15919
    ImGuiDockNode*      CentralNode;
15920
    ImGuiDockNode*      FirstNodeWithWindows;
15921
    int                 CountNodesWithWindows;
15922
    //ImGuiWindowClass  WindowClassForMerges;
15923
15924
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
15925
};
15926
15927
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
15928
0
{
15929
0
    if (node->Windows.Size > 0)
15930
0
    {
15931
0
        if (info->FirstNodeWithWindows == NULL)
15932
0
            info->FirstNodeWithWindows = node;
15933
0
        info->CountNodesWithWindows++;
15934
0
    }
15935
0
    if (node->IsCentralNode())
15936
0
    {
15937
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
15938
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
15939
0
        info->CentralNode = node;
15940
0
    }
15941
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
15942
0
        return;
15943
0
    if (node->ChildNodes[0])
15944
0
        DockNodeFindInfo(node->ChildNodes[0], info);
15945
0
    if (node->ChildNodes[1])
15946
0
        DockNodeFindInfo(node->ChildNodes[1], info);
15947
0
}
15948
15949
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
15950
0
{
15951
0
    IM_ASSERT(id != 0);
15952
0
    for (int n = 0; n < node->Windows.Size; n++)
15953
0
        if (node->Windows[n]->ID == id)
15954
0
            return node->Windows[n];
15955
0
    return NULL;
15956
0
}
15957
15958
// - Remove inactive windows/nodes.
15959
// - Update visibility flag.
15960
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
15961
0
{
15962
0
    ImGuiContext& g = *GImGui;
15963
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15964
15965
    // Inherit most flags
15966
0
    if (node->ParentNode)
15967
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
15968
15969
    // Recurse into children
15970
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
15971
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
15972
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
15973
0
    node->HasCentralNodeChild = false;
15974
0
    if (node->ChildNodes[0])
15975
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
15976
0
    if (node->ChildNodes[1])
15977
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
15978
15979
    // Remove inactive windows, collapse nodes
15980
    // Merge node flags overrides stored in windows
15981
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
15982
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
15983
0
    {
15984
0
        ImGuiWindow* window = node->Windows[window_n];
15985
0
        IM_ASSERT(window->DockNode == node);
15986
15987
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
15988
0
        bool remove = false;
15989
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
15990
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
15991
0
        remove |= (window->DockTabWantClose);
15992
0
        if (remove)
15993
0
        {
15994
0
            window->DockTabWantClose = false;
15995
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
15996
0
            {
15997
0
                DockNodeHideHostWindow(node);
15998
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
15999
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
16000
0
                return;
16001
0
            }
16002
0
            DockNodeRemoveWindow(node, window, node->ID);
16003
0
            window_n--;
16004
0
            continue;
16005
0
        }
16006
16007
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
16008
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
16009
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
16010
0
    }
16011
0
    node->UpdateMergedFlags();
16012
16013
    // Auto-hide tab bar option
16014
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
16015
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
16016
0
        node->WantHiddenTabBarToggle = true;
16017
0
    node->WantHiddenTabBarUpdate = false;
16018
16019
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
16020
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
16021
0
        node->WantHiddenTabBarToggle = false;
16022
16023
    // Apply toggles at a single point of the frame (here!)
16024
0
    if (node->Windows.Size > 1)
16025
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16026
0
    else if (node->WantHiddenTabBarToggle)
16027
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
16028
0
    node->WantHiddenTabBarToggle = false;
16029
16030
0
    DockNodeUpdateVisibleFlag(node);
16031
0
}
16032
16033
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
16034
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
16035
0
{
16036
0
    node->HasCentralNodeChild = false;
16037
0
    if (node->ChildNodes[0])
16038
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
16039
0
    if (node->ChildNodes[1])
16040
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
16041
0
    if (node->IsRootNode())
16042
0
    {
16043
0
        ImGuiDockNode* mark_node = node->CentralNode;
16044
0
        while (mark_node)
16045
0
        {
16046
0
            mark_node->HasCentralNodeChild = true;
16047
0
            mark_node = mark_node->ParentNode;
16048
0
        }
16049
0
    }
16050
0
}
16051
16052
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
16053
0
{
16054
    // Update visibility flag
16055
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
16056
0
    is_visible |= (node->Windows.Size > 0);
16057
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
16058
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
16059
0
    node->IsVisible = is_visible;
16060
0
}
16061
16062
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
16063
0
{
16064
0
    ImGuiContext& g = *GImGui;
16065
0
    IM_ASSERT(node->WantMouseMove == true);
16066
0
    StartMouseMovingWindow(window);
16067
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
16068
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
16069
0
    node->WantMouseMove = false;
16070
0
}
16071
16072
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
16073
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
16074
0
{
16075
0
    DockNodeUpdateFlagsAndCollapse(node);
16076
16077
    // - Setup central node pointers
16078
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
16079
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
16080
0
    ImGuiDockNodeTreeInfo info;
16081
0
    DockNodeFindInfo(node, &info);
16082
0
    node->CentralNode = info.CentralNode;
16083
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
16084
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
16085
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
16086
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
16087
16088
    // Copy the window class from of our first window so it can be used for proper dock filtering.
16089
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
16090
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
16091
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
16092
0
    {
16093
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
16094
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
16095
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
16096
0
            {
16097
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
16098
0
                break;
16099
0
            }
16100
0
    }
16101
16102
0
    ImGuiDockNode* mark_node = node->CentralNode;
16103
0
    while (mark_node)
16104
0
    {
16105
0
        mark_node->HasCentralNodeChild = true;
16106
0
        mark_node = mark_node->ParentNode;
16107
0
    }
16108
0
}
16109
16110
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
16111
0
{
16112
    // Remove ourselves from any previous different host window
16113
    // This can happen if a user mistakenly does (see #4295 for details):
16114
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
16115
    //  - N+1: NewFrame()                   // will create floating host window for that node
16116
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
16117
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
16118
0
        node->HostWindow->DockNodeAsHost = NULL;
16119
16120
0
    host_window->DockNodeAsHost = node;
16121
0
    node->HostWindow = host_window;
16122
0
}
16123
16124
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
16125
0
{
16126
0
    ImGuiContext& g = *GImGui;
16127
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
16128
0
    node->LastFrameAlive = g.FrameCount;
16129
0
    node->IsBgDrawnThisFrame = false;
16130
16131
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
16132
0
    if (node->IsRootNode())
16133
0
        DockNodeUpdateForRootNode(node);
16134
16135
    // Remove tab bar if not needed
16136
0
    if (node->TabBar && node->IsNoTabBar())
16137
0
        DockNodeRemoveTabBar(node);
16138
16139
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
16140
0
    bool want_to_hide_host_window = false;
16141
0
    if (node->IsFloatingNode())
16142
0
    {
16143
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
16144
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
16145
0
                want_to_hide_host_window = true;
16146
0
        if (node->CountNodeWithWindows == 0)
16147
0
            want_to_hide_host_window = true;
16148
0
    }
16149
0
    if (want_to_hide_host_window)
16150
0
    {
16151
0
        if (node->Windows.Size == 1)
16152
0
        {
16153
            // Floating window pos/size is authoritative
16154
0
            ImGuiWindow* single_window = node->Windows[0];
16155
0
            node->Pos = single_window->Pos;
16156
0
            node->Size = single_window->SizeFull;
16157
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
16158
16159
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
16160
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
16161
0
                FocusWindow(single_window);
16162
0
            if (node->HostWindow)
16163
0
            {
16164
0
                single_window->Viewport = node->HostWindow->Viewport;
16165
0
                single_window->ViewportId = node->HostWindow->ViewportId;
16166
0
                if (node->HostWindow->ViewportOwned)
16167
0
                {
16168
0
                    single_window->Viewport->Window = single_window;
16169
0
                    single_window->ViewportOwned = true;
16170
0
                }
16171
0
            }
16172
0
        }
16173
16174
0
        DockNodeHideHostWindow(node);
16175
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16176
0
        node->WantCloseAll = false;
16177
0
        node->WantCloseTabId = 0;
16178
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
16179
0
        node->LastFrameActive = g.FrameCount;
16180
16181
0
        if (node->WantMouseMove && node->Windows.Size == 1)
16182
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
16183
0
        return;
16184
0
    }
16185
16186
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
16187
    // while the expected visible window is resizing itself.
16188
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
16189
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
16190
    //   N+0: Begin(): window created (with no known size), node is created
16191
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
16192
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
16193
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
16194
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
16195
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
16196
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
16197
0
    {
16198
0
        IM_ASSERT(node->Windows.Size > 0);
16199
0
        ImGuiWindow* ref_window = NULL;
16200
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
16201
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
16202
0
        if (ref_window == NULL)
16203
0
            ref_window = node->Windows[0];
16204
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
16205
0
        {
16206
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
16207
0
            return;
16208
0
        }
16209
0
    }
16210
16211
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16212
16213
    // Decide if the node will have a close button and a window menu button
16214
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
16215
0
    node->HasCloseButton = false;
16216
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16217
0
    {
16218
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
16219
0
        ImGuiWindow* window = node->Windows[window_n];
16220
0
        node->HasCloseButton |= window->HasCloseButton;
16221
0
        window->DockIsActive = (node->Windows.Size > 1);
16222
0
    }
16223
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
16224
0
        node->HasCloseButton = false;
16225
16226
    // Bind or create host window
16227
0
    ImGuiWindow* host_window = NULL;
16228
0
    bool beginned_into_host_window = false;
16229
0
    if (node->IsDockSpace())
16230
0
    {
16231
        // [Explicit root dockspace node]
16232
0
        IM_ASSERT(node->HostWindow);
16233
0
        host_window = node->HostWindow;
16234
0
    }
16235
0
    else
16236
0
    {
16237
        // [Automatic root or child nodes]
16238
0
        if (node->IsRootNode() && node->IsVisible)
16239
0
        {
16240
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16241
16242
            // Sync Pos
16243
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
16244
0
                SetNextWindowPos(ref_window->Pos);
16245
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
16246
0
                SetNextWindowPos(node->Pos);
16247
16248
            // Sync Size
16249
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16250
0
                SetNextWindowSize(ref_window->SizeFull);
16251
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
16252
0
                SetNextWindowSize(node->Size);
16253
16254
            // Sync Collapsed
16255
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16256
0
                SetNextWindowCollapsed(ref_window->Collapsed);
16257
16258
            // Sync Viewport
16259
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
16260
0
                SetNextWindowViewport(ref_window->ViewportId);
16261
16262
0
            SetNextWindowClass(&node->WindowClass);
16263
16264
            // Begin into the host window
16265
0
            char window_label[20];
16266
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
16267
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
16268
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
16269
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
16270
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
16271
16272
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
16273
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
16274
0
            Begin(window_label, NULL, window_flags);
16275
0
            PopStyleVar();
16276
0
            beginned_into_host_window = true;
16277
16278
0
            host_window = g.CurrentWindow;
16279
0
            DockNodeSetupHostWindow(node, host_window);
16280
0
            host_window->DC.CursorPos = host_window->Pos;
16281
0
            node->Pos = host_window->Pos;
16282
0
            node->Size = host_window->Size;
16283
16284
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
16285
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
16286
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
16287
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
16288
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
16289
            // after the dock host window, losing their top-most status.
16290
0
            if (node->HostWindow->Appearing)
16291
0
                BringWindowToDisplayFront(node->HostWindow);
16292
16293
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16294
0
        }
16295
0
        else if (node->ParentNode)
16296
0
        {
16297
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
16298
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16299
0
        }
16300
0
        if (node->WantMouseMove && node->HostWindow)
16301
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
16302
0
    }
16303
16304
    // Update focused node (the one whose title bar is highlight) within a node tree
16305
0
    if (node->IsSplitNode())
16306
0
        IM_ASSERT(node->TabBar == NULL);
16307
0
    if (node->IsRootNode())
16308
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
16309
0
            while (p_window != NULL && p_window->DockNode != NULL)
16310
0
            {
16311
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
16312
0
                if (p_node == node)
16313
0
                {
16314
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
16315
0
                    break;
16316
0
                }
16317
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
16318
0
            }
16319
16320
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
16321
0
    ImGuiDockNode* central_node = node->CentralNode;
16322
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
16323
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
16324
0
    if (central_node_hole)
16325
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
16326
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
16327
0
                central_node_hole_register_hit_test_hole = false;
16328
0
    if (central_node_hole_register_hit_test_hole)
16329
0
    {
16330
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
16331
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
16332
        // covering passthru node we'd have a gap on the edge not covered by the hole)
16333
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
16334
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
16335
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
16336
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
16337
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
16338
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
16339
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
16340
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
16341
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
16342
0
        if (central_node_hole && !hole_rect.IsInverted())
16343
0
        {
16344
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16345
0
            if (host_window->ParentWindow)
16346
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16347
0
        }
16348
0
    }
16349
16350
    // Update position/size, process and draw resizing splitters
16351
0
    if (node->IsRootNode() && host_window)
16352
0
    {
16353
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
16354
0
        DockNodeTreeUpdateSplitter(node);
16355
0
    }
16356
16357
    // Draw empty node background (currently can only be the Central Node)
16358
0
    if (host_window && node->IsEmpty() && node->IsVisible)
16359
0
    {
16360
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16361
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
16362
0
        if (node->LastBgColor != 0)
16363
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
16364
0
        node->IsBgDrawnThisFrame = true;
16365
0
    }
16366
16367
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
16368
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
16369
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
16370
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
16371
0
    if (render_dockspace_bg && node->IsVisible)
16372
0
    {
16373
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16374
0
        if (central_node_hole)
16375
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
16376
0
        else
16377
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
16378
0
    }
16379
16380
    // Draw and populate Tab Bar
16381
0
    if (host_window)
16382
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
16383
0
    if (host_window && node->Windows.Size > 0)
16384
0
    {
16385
0
        DockNodeUpdateTabBar(node, host_window);
16386
0
    }
16387
0
    else
16388
0
    {
16389
0
        node->WantCloseAll = false;
16390
0
        node->WantCloseTabId = 0;
16391
0
        node->IsFocused = false;
16392
0
    }
16393
0
    if (node->TabBar && node->TabBar->SelectedTabId)
16394
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
16395
0
    else if (node->Windows.Size > 0)
16396
0
        node->SelectedTabId = node->Windows[0]->TabId;
16397
16398
    // Draw payload drop target
16399
0
    if (host_window && node->IsVisible)
16400
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
16401
0
            BeginDockableDragDropTarget(host_window);
16402
16403
    // We update this after DockNodeUpdateTabBar()
16404
0
    node->LastFrameActive = g.FrameCount;
16405
16406
    // Recurse into children
16407
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
16408
0
    if (host_window)
16409
0
    {
16410
0
        if (node->ChildNodes[0])
16411
0
            DockNodeUpdate(node->ChildNodes[0]);
16412
0
        if (node->ChildNodes[1])
16413
0
            DockNodeUpdate(node->ChildNodes[1]);
16414
16415
        // Render outer borders last (after the tab bar)
16416
0
        if (node->IsRootNode())
16417
0
            RenderWindowOuterBorders(host_window);
16418
0
    }
16419
16420
    // End host window
16421
0
    if (beginned_into_host_window) //-V1020
16422
0
        End();
16423
0
}
16424
16425
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
16426
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
16427
0
{
16428
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
16429
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
16430
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
16431
0
        return d;
16432
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
16433
0
}
16434
16435
// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
16436
// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
16437
// Custom overrides may want to decorate, group, sort entries.
16438
// Please note those are internal structures: if you copy this expect occasional breakage.
16439
void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16440
0
{
16441
0
    IM_UNUSED(ctx);
16442
0
    if (tab_bar->Tabs.Size == 1)
16443
0
    {
16444
        // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
16445
0
        if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
16446
0
            node->WantHiddenTabBarToggle = true;
16447
0
    }
16448
0
    else
16449
0
    {
16450
        // Display a selectable list of windows in this docking node
16451
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
16452
0
        {
16453
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
16454
0
            if (tab->Flags & ImGuiTabItemFlags_Button)
16455
0
                continue;
16456
0
            if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
16457
0
                TabBarQueueFocus(tab_bar, tab);
16458
0
            SameLine();
16459
0
            Text("   ");
16460
0
        }
16461
0
    }
16462
0
}
16463
16464
static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16465
0
{
16466
    // Try to position the menu so it is more likely to stays within the same viewport
16467
0
    ImGuiContext& g = *GImGui;
16468
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
16469
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
16470
0
    else
16471
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
16472
0
    if (BeginPopup("#WindowMenu"))
16473
0
    {
16474
0
        node->IsFocused = true;
16475
0
        g.DockNodeWindowMenuHandler(&g, node, tab_bar);
16476
0
        EndPopup();
16477
0
    }
16478
0
}
16479
16480
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
16481
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
16482
0
{
16483
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
16484
0
        return false;
16485
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
16486
0
        return false;
16487
0
    Begin(node->HostWindow->Name);
16488
0
    PushOverrideID(node->ID);
16489
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags, node);
16490
0
    IM_UNUSED(ret);
16491
0
    IM_ASSERT(ret);
16492
0
    return true;
16493
0
}
16494
16495
void ImGui::DockNodeEndAmendTabBar()
16496
0
{
16497
0
    EndTabBar();
16498
0
    PopID();
16499
0
    End();
16500
0
}
16501
16502
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
16503
0
{
16504
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
16505
0
    ImGuiContext& g = *GImGui;
16506
0
    if (g.NavWindowingTarget)
16507
0
        return (g.NavWindowingTarget->DockNode == node);
16508
16509
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
16510
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
16511
0
    {
16512
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
16513
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
16514
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
16515
0
            parent_window = parent_window->ParentWindow->RootWindow;
16516
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
16517
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
16518
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
16519
0
                return true;
16520
0
    }
16521
0
    return false;
16522
0
}
16523
16524
// Submit the tab bar corresponding to a dock node and various housekeeping details.
16525
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
16526
0
{
16527
0
    ImGuiContext& g = *GImGui;
16528
0
    ImGuiStyle& style = g.Style;
16529
16530
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16531
0
    const bool closed_all = node->WantCloseAll && node_was_active;
16532
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
16533
0
    node->WantCloseAll = false;
16534
0
    node->WantCloseTabId = 0;
16535
16536
    // Decide if we should use a focused title bar color
16537
0
    bool is_focused = false;
16538
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16539
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
16540
0
        is_focused = true;
16541
16542
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
16543
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
16544
0
    {
16545
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16546
0
        node->IsFocused = is_focused;
16547
0
        if (is_focused)
16548
0
            node->LastFrameFocused = g.FrameCount;
16549
0
        if (node->VisibleWindow)
16550
0
        {
16551
            // Notify root of visible window (used to display title in OS task bar)
16552
0
            if (is_focused || root_node->VisibleWindow == NULL)
16553
0
                root_node->VisibleWindow = node->VisibleWindow;
16554
0
            if (node->TabBar)
16555
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
16556
0
        }
16557
0
        return;
16558
0
    }
16559
16560
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
16561
0
    bool backup_skip_item = host_window->SkipItems;
16562
0
    if (!node->IsDockSpace())
16563
0
    {
16564
0
        host_window->SkipItems = false;
16565
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
16566
0
    }
16567
16568
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
16569
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
16570
    // as docked windows themselves will override the stack with their own root ID.
16571
0
    PushOverrideID(node->ID);
16572
0
    ImGuiTabBar* tab_bar = node->TabBar;
16573
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
16574
0
    if (tab_bar == NULL)
16575
0
    {
16576
0
        DockNodeAddTabBar(node);
16577
0
        tab_bar = node->TabBar;
16578
0
    }
16579
16580
0
    ImGuiID focus_tab_id = 0;
16581
0
    node->IsFocused = is_focused;
16582
16583
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16584
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
16585
16586
    // In a dock node, the Collapse Button turns into the Window Menu button.
16587
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
16588
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
16589
0
    {
16590
0
        ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
16591
0
        DockNodeWindowMenuUpdate(node, tab_bar);
16592
0
        if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
16593
0
            focus_tab_id = tab_bar->NextSelectedTabId;
16594
0
        is_focused |= node->IsFocused;
16595
0
    }
16596
16597
    // Layout
16598
0
    ImRect title_bar_rect, tab_bar_rect;
16599
0
    ImVec2 window_menu_button_pos;
16600
0
    ImVec2 close_button_pos;
16601
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
16602
16603
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
16604
0
    const int tabs_count_old = tab_bar->Tabs.Size;
16605
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16606
0
    {
16607
0
        ImGuiWindow* window = node->Windows[window_n];
16608
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
16609
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
16610
0
    }
16611
16612
    // Title bar
16613
0
    if (is_focused)
16614
0
        node->LastFrameFocused = g.FrameCount;
16615
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
16616
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE);
16617
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
16618
16619
    // Docking/Collapse button
16620
0
    if (has_window_menu_button)
16621
0
    {
16622
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
16623
0
            OpenPopup("#WindowMenu");
16624
0
        if (IsItemActive())
16625
0
            focus_tab_id = tab_bar->SelectedTabId;
16626
0
    }
16627
16628
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
16629
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
16630
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
16631
0
    {
16632
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
16633
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
16634
0
        tabs_unsorted_start = tab_n;
16635
0
    }
16636
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
16637
0
    {
16638
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
16639
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
16640
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab '%s' Order %d\n", tab_bar->Tabs[tab_n].Window->Name, tab_bar->Tabs[tab_n].Window->DockOrder);
16641
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
16642
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
16643
0
    }
16644
16645
    // Apply NavWindow focus back to the tab bar
16646
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
16647
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
16648
16649
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
16650
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
16651
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
16652
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
16653
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
16654
16655
    // Begin tab bar
16656
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
16657
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;
16658
0
    if (!host_window->Collapsed && is_focused)
16659
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
16660
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags, node);
16661
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
16662
16663
    // Backup style colors
16664
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
16665
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16666
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
16667
16668
    // Submit actual tabs
16669
0
    node->VisibleWindow = NULL;
16670
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16671
0
    {
16672
0
        ImGuiWindow* window = node->Windows[window_n];
16673
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
16674
0
            continue;
16675
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
16676
0
        {
16677
0
            ImGuiTabItemFlags tab_item_flags = 0;
16678
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
16679
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
16680
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
16681
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
16682
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
16683
16684
            // Apply stored style overrides for the window
16685
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16686
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
16687
16688
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
16689
0
            bool tab_open = true;
16690
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
16691
0
            if (!tab_open)
16692
0
                node->WantCloseTabId = window->TabId;
16693
0
            if (tab_bar->VisibleTabId == window->TabId)
16694
0
                node->VisibleWindow = window;
16695
16696
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
16697
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
16698
0
            window->DockTabItemRect = g.LastItemData.Rect;
16699
16700
            // Update navigation ID on menu layer
16701
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
16702
0
                host_window->NavLastIds[1] = window->TabId;
16703
0
        }
16704
0
    }
16705
16706
    // Restore style colors
16707
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16708
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
16709
16710
    // Notify root of visible window (used to display title in OS task bar)
16711
0
    if (node->VisibleWindow)
16712
0
        if (is_focused || root_node->VisibleWindow == NULL)
16713
0
            root_node->VisibleWindow = node->VisibleWindow;
16714
16715
    // Close button (after VisibleWindow was updated)
16716
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
16717
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
16718
0
    const bool close_button_is_visible = node->HasCloseButton;
16719
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
16720
0
    if (close_button_is_visible)
16721
0
    {
16722
0
        if (!close_button_is_enabled)
16723
0
        {
16724
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
16725
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
16726
0
        }
16727
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
16728
0
        {
16729
0
            node->WantCloseAll = true;
16730
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
16731
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
16732
0
        }
16733
        //if (IsItemActive())
16734
        //    focus_tab_id = tab_bar->SelectedTabId;
16735
0
        if (!close_button_is_enabled)
16736
0
        {
16737
0
            PopStyleColor();
16738
0
            PopItemFlag();
16739
0
        }
16740
0
    }
16741
16742
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
16743
    // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
16744
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
16745
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
16746
0
    {
16747
0
        bool held;
16748
0
        KeepAliveID(title_bar_id);
16749
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowItemOverlap);
16750
0
        if (g.HoveredId == title_bar_id)
16751
0
        {
16752
            // ImGuiButtonFlags_AllowItemOverlap + SetItemAllowOverlap() required for appending into dock node tab bar,
16753
            // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
16754
0
            g.LastItemData.ID = title_bar_id;
16755
0
            SetItemAllowOverlap();
16756
0
        }
16757
0
        if (held)
16758
0
        {
16759
0
            if (IsMouseClicked(0))
16760
0
                focus_tab_id = tab_bar->SelectedTabId;
16761
16762
            // Forward moving request to selected window
16763
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
16764
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false);
16765
0
        }
16766
0
    }
16767
16768
    // Forward focus from host node to selected window
16769
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
16770
    //    focus_tab_id = tab_bar->SelectedTabId;
16771
16772
    // When clicked on a tab we requested focus to the docked child
16773
    // This overrides the value set by "forward focus from host node to selected window".
16774
0
    if (tab_bar->NextSelectedTabId)
16775
0
        focus_tab_id = tab_bar->NextSelectedTabId;
16776
16777
    // Apply navigation focus
16778
0
    if (focus_tab_id != 0)
16779
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
16780
0
            if (tab->Window)
16781
0
            {
16782
0
                FocusWindow(tab->Window);
16783
0
                NavInitWindow(tab->Window, false);
16784
0
            }
16785
16786
0
    EndTabBar();
16787
0
    PopID();
16788
16789
    // Restore SkipItems flag
16790
0
    if (!node->IsDockSpace())
16791
0
    {
16792
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
16793
0
        host_window->SkipItems = backup_skip_item;
16794
0
    }
16795
0
}
16796
16797
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
16798
0
{
16799
0
    IM_ASSERT(node->TabBar == NULL);
16800
0
    node->TabBar = IM_NEW(ImGuiTabBar);
16801
0
}
16802
16803
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
16804
0
{
16805
0
    if (node->TabBar == NULL)
16806
0
        return;
16807
0
    IM_DELETE(node->TabBar);
16808
0
    node->TabBar = NULL;
16809
0
}
16810
16811
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
16812
0
{
16813
0
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
16814
0
        return false;
16815
16816
0
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
16817
0
    ImGuiWindowClass* payload_class = &payload->WindowClass;
16818
0
    if (host_class->ClassId != payload_class->ClassId)
16819
0
    {
16820
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
16821
0
            return true;
16822
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
16823
0
            return true;
16824
0
        return false;
16825
0
    }
16826
16827
    // Prevent docking any window created above a popup
16828
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
16829
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
16830
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
16831
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
16832
0
    ImGuiContext& g = *GImGui;
16833
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
16834
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
16835
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
16836
0
                return false;
16837
16838
0
    return true;
16839
0
}
16840
16841
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
16842
0
{
16843
0
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
16844
0
        return true;
16845
16846
0
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
16847
0
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
16848
0
    {
16849
0
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
16850
0
        if (DockNodeIsDropAllowedOne(payload, host_window))
16851
0
            return true;
16852
0
    }
16853
0
    return false;
16854
0
}
16855
16856
// window menu button == collapse button when not in a dock node.
16857
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
16858
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
16859
0
{
16860
0
    ImGuiContext& g = *GImGui;
16861
0
    ImGuiStyle& style = g.Style;
16862
16863
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
16864
0
    if (out_title_rect) { *out_title_rect = r; }
16865
16866
0
    r.Min.x += style.WindowBorderSize;
16867
0
    r.Max.x -= style.WindowBorderSize;
16868
16869
0
    float button_sz = g.FontSize;
16870
16871
0
    ImVec2 window_menu_button_pos = r.Min;
16872
0
    r.Min.x += style.FramePadding.x;
16873
0
    r.Max.x -= style.FramePadding.x;
16874
0
    if (node->HasCloseButton)
16875
0
    {
16876
0
        r.Max.x -= button_sz;
16877
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - style.FramePadding.x, r.Min.y);
16878
0
    }
16879
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
16880
0
    {
16881
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
16882
0
    }
16883
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
16884
0
    {
16885
0
        r.Max.x -= button_sz + style.FramePadding.x;
16886
0
        window_menu_button_pos = ImVec2(r.Max.x, r.Min.y);
16887
0
    }
16888
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
16889
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
16890
0
}
16891
16892
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
16893
0
{
16894
0
    ImGuiContext& g = *GImGui;
16895
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
16896
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16897
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
16898
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
16899
16900
    // Distribute size on given axis (with a desired size or equally)
16901
0
    const float w_avail = size_old[axis] - dock_spacing;
16902
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
16903
0
    {
16904
0
        size_new[axis] = size_new_desired[axis];
16905
0
        size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
16906
0
    }
16907
0
    else
16908
0
    {
16909
0
        size_new[axis] = IM_FLOOR(w_avail * 0.5f);
16910
0
        size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
16911
0
    }
16912
16913
    // Position each node
16914
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
16915
0
    {
16916
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
16917
0
    }
16918
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
16919
0
    {
16920
0
        pos_new[axis] = pos_old[axis];
16921
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
16922
0
    }
16923
0
}
16924
16925
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
16926
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
16927
0
{
16928
0
    ImGuiContext& g = *GImGui;
16929
16930
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
16931
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
16932
0
    float hs_w; // Half-size, longer axis
16933
0
    float hs_h; // Half-size, smaller axis
16934
0
    ImVec2 off; // Distance from edge or center
16935
0
    if (outer_docking)
16936
0
    {
16937
        //hs_w = ImFloor(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
16938
        //hs_h = ImFloor(hs_w * 0.15f);
16939
        //off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImFloor(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
16940
0
        hs_w = ImFloor(hs_for_central_nodes * 1.50f);
16941
0
        hs_h = ImFloor(hs_for_central_nodes * 0.80f);
16942
0
        off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - hs_h), ImFloor(parent.GetHeight() * 0.5f - hs_h));
16943
0
    }
16944
0
    else
16945
0
    {
16946
0
        hs_w = ImFloor(hs_for_central_nodes);
16947
0
        hs_h = ImFloor(hs_for_central_nodes * 0.90f);
16948
0
        off = ImVec2(ImFloor(hs_w * 2.40f), ImFloor(hs_w * 2.40f));
16949
0
    }
16950
16951
0
    ImVec2 c = ImFloor(parent.GetCenter());
16952
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
16953
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
16954
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
16955
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
16956
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
16957
16958
0
    if (test_mouse_pos == NULL)
16959
0
        return false;
16960
16961
0
    ImRect hit_r = out_r;
16962
0
    if (!outer_docking)
16963
0
    {
16964
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
16965
0
        hit_r.Expand(ImFloor(hs_w * 0.30f));
16966
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
16967
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
16968
0
        float r_threshold_center = hs_w * 1.4f;
16969
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
16970
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
16971
0
            return (dir == ImGuiDir_None);
16972
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
16973
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
16974
0
    }
16975
0
    return hit_r.Contains(*test_mouse_pos);
16976
0
}
16977
16978
// host_node may be NULL if the window doesn't have a DockNode already.
16979
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
16980
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
16981
0
{
16982
0
    ImGuiContext& g = *GImGui;
16983
16984
    // There is an edge case when docking into a dockspace which only has inactive nodes.
16985
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
16986
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
16987
0
    if (payload_node == NULL)
16988
0
        payload_node = payload_window->DockNodeAsHost;
16989
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
16990
0
    if (ref_node_for_rect)
16991
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
16992
16993
    // Filter, figure out where we are allowed to dock
16994
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
16995
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
16996
0
    data->IsCenterAvailable = true;
16997
0
    if (is_outer_docking)
16998
0
        data->IsCenterAvailable = false;
16999
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDocking)
17000
0
        data->IsCenterAvailable = false;
17001
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode())
17002
0
        data->IsCenterAvailable = false;
17003
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
17004
0
        data->IsCenterAvailable = false;
17005
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
17006
0
        data->IsCenterAvailable = false;
17007
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
17008
0
        data->IsCenterAvailable = false;
17009
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
17010
0
        data->IsCenterAvailable = false;
17011
17012
0
    data->IsSidesAvailable = true;
17013
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoSplit) || g.IO.ConfigDockingNoSplit)
17014
0
        data->IsSidesAvailable = false;
17015
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
17016
0
        data->IsSidesAvailable = false;
17017
0
    else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplitMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther))
17018
0
        data->IsSidesAvailable = false;
17019
17020
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
17021
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
17022
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
17023
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
17024
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
17025
17026
    // Calculate drop shapes geometry for allowed splitting directions
17027
0
    IM_ASSERT(ImGuiDir_None == -1);
17028
0
    data->SplitNode = host_node;
17029
0
    data->SplitDir = ImGuiDir_None;
17030
0
    data->IsSplitDirExplicit = false;
17031
0
    if (!host_window->Collapsed)
17032
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17033
0
        {
17034
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
17035
0
                continue;
17036
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
17037
0
                continue;
17038
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
17039
0
            {
17040
0
                data->SplitDir = (ImGuiDir)dir;
17041
0
                data->IsSplitDirExplicit = true;
17042
0
            }
17043
0
        }
17044
17045
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
17046
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
17047
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
17048
0
        data->IsDropAllowed = false;
17049
17050
    // Calculate split area
17051
0
    data->SplitRatio = 0.0f;
17052
0
    if (data->SplitDir != ImGuiDir_None)
17053
0
    {
17054
0
        ImGuiDir split_dir = data->SplitDir;
17055
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17056
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
17057
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
17058
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
17059
17060
        // Calculate split ratio so we can pass it down the docking request
17061
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
17062
0
        data->FutureNode.Pos = pos_new;
17063
0
        data->FutureNode.Size = size_new;
17064
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
17065
0
    }
17066
0
}
17067
17068
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
17069
0
{
17070
0
    ImGuiContext& g = *GImGui;
17071
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
17072
17073
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
17074
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
17075
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
17076
17077
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
17078
0
    int overlay_draw_lists_count = 0;
17079
0
    ImDrawList* overlay_draw_lists[2];
17080
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
17081
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
17082
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
17083
17084
    // Draw main preview rectangle
17085
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
17086
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
17087
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
17088
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
17089
17090
    // Display area preview
17091
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
17092
0
    if (data->IsDropAllowed)
17093
0
    {
17094
0
        ImRect overlay_rect = data->FutureNode.Rect();
17095
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
17096
0
            overlay_rect.Min.y += GetFrameHeight();
17097
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
17098
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17099
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE));
17100
0
    }
17101
17102
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
17103
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
17104
0
    {
17105
        // Compute target tab bar geometry so we can locate our preview tabs
17106
0
        ImRect tab_bar_rect;
17107
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
17108
0
        ImVec2 tab_pos = tab_bar_rect.Min;
17109
0
        if (host_node && host_node->TabBar)
17110
0
        {
17111
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
17112
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
17113
0
            else
17114
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
17115
0
        }
17116
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
17117
0
        {
17118
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
17119
0
        }
17120
17121
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
17122
0
        if (root_payload->DockNodeAsHost)
17123
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
17124
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
17125
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
17126
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
17127
0
        {
17128
            // DockNode's TabBar may have non-window Tabs manually appended by user
17129
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
17130
0
            if (tab_bar_with_payload && payload_window == NULL)
17131
0
                continue;
17132
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
17133
0
                continue;
17134
17135
            // Calculate the tab bounding box for each payload window
17136
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
17137
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
17138
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
17139
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
17140
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
17141
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
17142
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17143
0
            {
17144
0
                ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_Preview | ((payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0);
17145
0
                if (!tab_bar_rect.Contains(tab_bb))
17146
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
17147
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
17148
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
17149
0
                if (!tab_bar_rect.Contains(tab_bb))
17150
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
17151
0
            }
17152
0
            PopStyleColor();
17153
0
        }
17154
0
    }
17155
17156
    // Display drop boxes
17157
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
17158
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17159
0
    {
17160
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
17161
0
        {
17162
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
17163
0
            ImRect draw_r_in = draw_r;
17164
0
            draw_r_in.Expand(-2.0f);
17165
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
17166
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17167
0
            {
17168
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
17169
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
17170
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
17171
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
17172
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
17173
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
17174
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
17175
0
            }
17176
0
        }
17177
17178
        // Stop after ImGuiDir_None
17179
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit)
17180
0
            return;
17181
0
    }
17182
0
}
17183
17184
//-----------------------------------------------------------------------------
17185
// Docking: ImGuiDockNode Tree manipulation functions
17186
//-----------------------------------------------------------------------------
17187
// - DockNodeTreeSplit()
17188
// - DockNodeTreeMerge()
17189
// - DockNodeTreeUpdatePosSize()
17190
// - DockNodeTreeUpdateSplitterFindTouchingNode()
17191
// - DockNodeTreeUpdateSplitter()
17192
// - DockNodeTreeFindFallbackLeafNode()
17193
// - DockNodeTreeFindNodeByPos()
17194
//-----------------------------------------------------------------------------
17195
17196
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
17197
0
{
17198
0
    ImGuiContext& g = *GImGui;
17199
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
17200
17201
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
17202
0
    child_0->ParentNode = parent_node;
17203
17204
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
17205
0
    child_1->ParentNode = parent_node;
17206
17207
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
17208
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
17209
0
    parent_node->ChildNodes[0] = child_0;
17210
0
    parent_node->ChildNodes[1] = child_1;
17211
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
17212
0
    parent_node->SplitAxis = split_axis;
17213
0
    parent_node->VisibleWindow = NULL;
17214
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17215
17216
0
    float size_avail = (parent_node->Size[split_axis] - DOCKING_SPLITTER_SIZE);
17217
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
17218
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
17219
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
17220
0
    child_0->SizeRef[split_axis] = ImFloor(size_avail * split_ratio);
17221
0
    child_1->SizeRef[split_axis] = ImFloor(size_avail - child_0->SizeRef[split_axis]);
17222
17223
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
17224
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
17225
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
17226
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
17227
17228
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
17229
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17230
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17231
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17232
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17233
0
    child_0->UpdateMergedFlags();
17234
0
    child_1->UpdateMergedFlags();
17235
0
    parent_node->UpdateMergedFlags();
17236
0
    if (child_inheritor->IsCentralNode())
17237
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
17238
0
}
17239
17240
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
17241
0
{
17242
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
17243
0
    ImGuiContext& g = *GImGui;
17244
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
17245
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
17246
0
    IM_ASSERT(child_0 || child_1);
17247
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
17248
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
17249
0
    {
17250
0
        IM_ASSERT(parent_node->TabBar == NULL);
17251
0
        IM_ASSERT(parent_node->Windows.Size == 0);
17252
0
    }
17253
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
17254
17255
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
17256
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
17257
0
    if (child_0)
17258
0
    {
17259
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
17260
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
17261
0
    }
17262
0
    if (child_1)
17263
0
    {
17264
0
        DockNodeMoveWindows(parent_node, child_1);
17265
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
17266
0
    }
17267
0
    DockNodeApplyPosSizeToWindows(parent_node);
17268
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17269
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
17270
0
    parent_node->SizeRef = backup_last_explicit_size;
17271
17272
    // Flags transfer
17273
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
17274
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17275
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17276
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
17277
0
    parent_node->UpdateMergedFlags();
17278
17279
0
    if (child_0)
17280
0
    {
17281
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
17282
0
        IM_DELETE(child_0);
17283
0
    }
17284
0
    if (child_1)
17285
0
    {
17286
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
17287
0
        IM_DELETE(child_1);
17288
0
    }
17289
0
}
17290
17291
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
17292
// (Depth-first, Pre-Order)
17293
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
17294
0
{
17295
    // During the regular dock node update we write to all nodes.
17296
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
17297
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
17298
0
    if (write_to_node)
17299
0
    {
17300
0
        node->Pos = pos;
17301
0
        node->Size = size;
17302
0
    }
17303
17304
0
    if (node->IsLeafNode())
17305
0
        return;
17306
17307
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17308
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17309
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
17310
0
    ImVec2 child_0_size = size, child_1_size = size;
17311
17312
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
17313
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
17314
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
17315
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
17316
17317
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
17318
0
    {
17319
0
        ImGuiContext& g = *GImGui;
17320
0
        const float spacing = DOCKING_SPLITTER_SIZE;
17321
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17322
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
17323
17324
        // Size allocation policy
17325
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
17326
0
        const float size_min_each = ImFloor(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
17327
17328
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
17329
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImFloor()
17330
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
17331
17332
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
17333
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
17334
0
        {
17335
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
17336
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17337
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17338
0
        }
17339
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
17340
0
        {
17341
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
17342
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
17343
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17344
0
        }
17345
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
17346
0
        {
17347
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
17348
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
17349
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
17350
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImFloor(size_avail * split_ratio);
17351
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17352
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17353
0
        }
17354
17355
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
17356
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
17357
0
        {
17358
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
17359
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17360
0
        }
17361
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
17362
0
        {
17363
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
17364
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
17365
0
        }
17366
0
        else
17367
0
        {
17368
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
17369
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
17370
0
            child_0_size[axis] = ImMax(size_min_each, ImFloor(size_avail * split_ratio + 0.5f));
17371
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17372
0
        }
17373
17374
0
        child_1_pos[axis] += spacing + child_0_size[axis];
17375
0
    }
17376
17377
0
    if (only_write_to_single_node == NULL)
17378
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
17379
17380
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
17381
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
17382
0
    if (child_0_recurse)
17383
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
17384
0
    if (child_1_recurse)
17385
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
17386
0
}
17387
17388
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
17389
0
{
17390
0
    if (node->IsLeafNode())
17391
0
    {
17392
0
        touching_nodes->push_back(node);
17393
0
        return;
17394
0
    }
17395
0
    if (node->ChildNodes[0]->IsVisible)
17396
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
17397
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
17398
0
    if (node->ChildNodes[1]->IsVisible)
17399
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
17400
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
17401
0
}
17402
17403
// (Depth-First, Pre-Order)
17404
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
17405
0
{
17406
0
    if (node->IsLeafNode())
17407
0
        return;
17408
17409
0
    ImGuiContext& g = *GImGui;
17410
17411
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17412
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17413
0
    if (child_0->IsVisible && child_1->IsVisible)
17414
0
    {
17415
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
17416
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17417
0
        IM_ASSERT(axis != ImGuiAxis_None);
17418
0
        ImRect bb;
17419
0
        bb.Min = child_0->Pos;
17420
0
        bb.Max = child_1->Pos;
17421
0
        bb.Min[axis] += child_0->Size[axis];
17422
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
17423
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
17424
17425
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
17426
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
17427
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
17428
0
        {
17429
0
            ImGuiWindow* window = g.CurrentWindow;
17430
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
17431
0
        }
17432
0
        else
17433
0
        {
17434
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
17435
            //bb.Max[axis] -= 1;
17436
0
            PushID(node->ID);
17437
17438
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
17439
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
17440
0
            float min_size = g.Style.WindowMinSize[axis];
17441
0
            float resize_limits[2];
17442
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
17443
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
17444
17445
0
            ImGuiID splitter_id = GetID("##Splitter");
17446
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
17447
0
            {
17448
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
17449
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
17450
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
17451
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
17452
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
17453
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
17454
17455
                // [DEBUG] Render touching nodes & limits
17456
                /*
17457
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17458
                for (int n = 0; n < 2; n++)
17459
                {
17460
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
17461
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
17462
                    if (axis == ImGuiAxis_X)
17463
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
17464
                    else
17465
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
17466
                }
17467
                */
17468
0
            }
17469
17470
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
17471
0
            float cur_size_0 = child_0->Size[axis];
17472
0
            float cur_size_1 = child_1->Size[axis];
17473
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
17474
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
17475
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
17476
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
17477
0
            {
17478
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
17479
0
                {
17480
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
17481
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
17482
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
17483
17484
                    // Lock the size of every node that is a sibling of the node we are touching
17485
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
17486
0
                    for (int side_n = 0; side_n < 2; side_n++)
17487
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
17488
0
                        {
17489
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
17490
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17491
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
17492
0
                            while (touching_node->ParentNode != node)
17493
0
                            {
17494
0
                                if (touching_node->ParentNode->SplitAxis == axis)
17495
0
                                {
17496
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
17497
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
17498
0
                                    node_to_preserve->WantLockSizeOnce = true;
17499
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
17500
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
17501
0
                                }
17502
0
                                touching_node = touching_node->ParentNode;
17503
0
                            }
17504
0
                        }
17505
17506
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
17507
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
17508
0
                    MarkIniSettingsDirty();
17509
0
                }
17510
0
            }
17511
0
            PopID();
17512
0
        }
17513
0
    }
17514
17515
0
    if (child_0->IsVisible)
17516
0
        DockNodeTreeUpdateSplitter(child_0);
17517
0
    if (child_1->IsVisible)
17518
0
        DockNodeTreeUpdateSplitter(child_1);
17519
0
}
17520
17521
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
17522
0
{
17523
0
    if (node->IsLeafNode())
17524
0
        return node;
17525
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
17526
0
        return leaf_node;
17527
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
17528
0
        return leaf_node;
17529
0
    return NULL;
17530
0
}
17531
17532
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
17533
0
{
17534
0
    if (!node->IsVisible)
17535
0
        return NULL;
17536
17537
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
17538
0
    ImRect r(node->Pos, node->Pos + node->Size);
17539
0
    r.Expand(dock_spacing * 0.5f);
17540
0
    bool inside = r.Contains(pos);
17541
0
    if (!inside)
17542
0
        return NULL;
17543
17544
0
    if (node->IsLeafNode())
17545
0
        return node;
17546
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
17547
0
        return hovered_node;
17548
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
17549
0
        return hovered_node;
17550
17551
    // This means we are hovering over the splitter/spacing of a parent node
17552
0
    return node;
17553
0
}
17554
17555
//-----------------------------------------------------------------------------
17556
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
17557
//-----------------------------------------------------------------------------
17558
// - SetWindowDock() [Internal]
17559
// - DockSpace()
17560
// - DockSpaceOverViewport()
17561
//-----------------------------------------------------------------------------
17562
17563
// [Internal] Called via SetNextWindowDockID()
17564
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
17565
0
{
17566
    // Test condition (NB: bit 0 is always true) and clear flags for next time
17567
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
17568
0
        return;
17569
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
17570
17571
0
    if (window->DockId == dock_id)
17572
0
        return;
17573
17574
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
17575
0
    ImGuiContext* ctx = GImGui;
17576
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx, dock_id))
17577
0
        if (new_node->IsSplitNode())
17578
0
        {
17579
            // Policy: Find central node or latest focused node. We first move back to our root node.
17580
0
            new_node = DockNodeGetRootNode(new_node);
17581
0
            if (new_node->CentralNode)
17582
0
            {
17583
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
17584
0
                dock_id = new_node->CentralNode->ID;
17585
0
            }
17586
0
            else
17587
0
            {
17588
0
                dock_id = new_node->LastFocusedNodeId;
17589
0
            }
17590
0
        }
17591
17592
0
    if (window->DockId == dock_id)
17593
0
        return;
17594
17595
0
    if (window->DockNode)
17596
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
17597
0
    window->DockId = dock_id;
17598
0
}
17599
17600
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
17601
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
17602
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
17603
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
17604
ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
17605
0
{
17606
0
    ImGuiContext* ctx = GImGui;
17607
0
    ImGuiContext& g = *ctx;
17608
0
    ImGuiWindow* window = GetCurrentWindowRead();
17609
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
17610
0
        return 0;
17611
17612
    // Early out if parent window is hidden/collapsed
17613
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
17614
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
17615
0
    if (window->SkipItems)
17616
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
17617
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
17618
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
17619
17620
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
17621
0
    IM_ASSERT(id != 0);
17622
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
17623
0
    if (!node)
17624
0
    {
17625
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", id);
17626
0
        node = DockContextAddNode(ctx, id);
17627
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
17628
0
    }
17629
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
17630
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
17631
0
    node->SharedFlags = flags;
17632
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
17633
17634
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
17635
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
17636
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
17637
0
    {
17638
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
17639
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17640
0
        return id;
17641
0
    }
17642
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17643
17644
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
17645
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
17646
0
    {
17647
0
        node->LastFrameAlive = g.FrameCount;
17648
0
        return id;
17649
0
    }
17650
17651
0
    const ImVec2 content_avail = GetContentRegionAvail();
17652
0
    ImVec2 size = ImFloor(size_arg);
17653
0
    if (size.x <= 0.0f)
17654
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
17655
0
    if (size.y <= 0.0f)
17656
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
17657
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17658
17659
0
    node->Pos = window->DC.CursorPos;
17660
0
    node->Size = node->SizeRef = size;
17661
0
    SetNextWindowPos(node->Pos);
17662
0
    SetNextWindowSize(node->Size);
17663
0
    g.NextWindowData.PosUndock = false;
17664
17665
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
17666
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
17667
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
17668
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
17669
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
17670
0
    window_flags |= ImGuiWindowFlags_NoBackground;
17671
17672
0
    char title[256];
17673
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
17674
17675
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
17676
0
    Begin(title, NULL, window_flags);
17677
0
    PopStyleVar();
17678
17679
0
    ImGuiWindow* host_window = g.CurrentWindow;
17680
0
    DockNodeSetupHostWindow(node, host_window);
17681
0
    host_window->ChildId = window->GetID(title);
17682
0
    node->OnlyNodeWithWindows = NULL;
17683
17684
0
    IM_ASSERT(node->IsRootNode());
17685
17686
    // We need to handle the rare case were a central node is missing.
17687
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
17688
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
17689
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
17690
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
17691
    // as it doesn't make sense for an empty dockspace to not have this property.
17692
0
    if (node->IsLeafNode() && !node->IsCentralNode())
17693
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17694
17695
    // Update the node
17696
0
    DockNodeUpdate(node);
17697
17698
0
    End();
17699
17700
0
    ImRect bb(node->Pos, node->Pos + size);
17701
0
    ItemSize(size);
17702
0
    ItemAdd(bb, id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
17703
0
    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
17704
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
17705
17706
0
    return id;
17707
0
}
17708
17709
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
17710
// The limitation with this call is that your window won't have a menu bar.
17711
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
17712
// But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
17713
ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
17714
0
{
17715
0
    if (viewport == NULL)
17716
0
        viewport = GetMainViewport();
17717
17718
0
    SetNextWindowPos(viewport->WorkPos);
17719
0
    SetNextWindowSize(viewport->WorkSize);
17720
0
    SetNextWindowViewport(viewport->ID);
17721
17722
0
    ImGuiWindowFlags host_window_flags = 0;
17723
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
17724
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
17725
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
17726
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
17727
17728
0
    char label[32];
17729
0
    ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
17730
17731
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
17732
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
17733
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
17734
0
    Begin(label, NULL, host_window_flags);
17735
0
    PopStyleVar(3);
17736
17737
0
    ImGuiID dockspace_id = GetID("DockSpace");
17738
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
17739
0
    End();
17740
17741
0
    return dockspace_id;
17742
0
}
17743
17744
//-----------------------------------------------------------------------------
17745
// Docking: Builder Functions
17746
//-----------------------------------------------------------------------------
17747
// Very early end-user API to manipulate dock nodes.
17748
// Only available in imgui_internal.h. Expect this API to change/break!
17749
// It is expected that those functions are all called _before_ the dockspace node submission.
17750
//-----------------------------------------------------------------------------
17751
// - DockBuilderDockWindow()
17752
// - DockBuilderGetNode()
17753
// - DockBuilderSetNodePos()
17754
// - DockBuilderSetNodeSize()
17755
// - DockBuilderAddNode()
17756
// - DockBuilderRemoveNode()
17757
// - DockBuilderRemoveNodeChildNodes()
17758
// - DockBuilderRemoveNodeDockedWindows()
17759
// - DockBuilderSplitNode()
17760
// - DockBuilderCopyNodeRec()
17761
// - DockBuilderCopyNode()
17762
// - DockBuilderCopyWindowSettings()
17763
// - DockBuilderCopyDockSpace()
17764
// - DockBuilderFinish()
17765
//-----------------------------------------------------------------------------
17766
17767
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
17768
0
{
17769
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
17770
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
17771
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
17772
0
    ImGuiID window_id = ImHashStr(window_name);
17773
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
17774
0
    {
17775
        // Apply to created window
17776
0
        ImGuiID prev_node_id = window->DockId;
17777
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
17778
0
        if (window->DockId != prev_node_id)
17779
0
            window->DockOrder = -1;
17780
0
    }
17781
0
    else
17782
0
    {
17783
        // Apply to settings
17784
0
        ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
17785
0
        if (settings == NULL)
17786
0
            settings = CreateNewWindowSettings(window_name);
17787
0
        if (settings->DockId != node_id)
17788
0
            settings->DockOrder = -1;
17789
0
        settings->DockId = node_id;
17790
0
    }
17791
0
}
17792
17793
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
17794
0
{
17795
0
    ImGuiContext* ctx = GImGui;
17796
0
    return DockContextFindNodeByID(ctx, node_id);
17797
0
}
17798
17799
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
17800
0
{
17801
0
    ImGuiContext* ctx = GImGui;
17802
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17803
0
    if (node == NULL)
17804
0
        return;
17805
0
    node->Pos = pos;
17806
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
17807
0
}
17808
17809
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
17810
0
{
17811
0
    ImGuiContext* ctx = GImGui;
17812
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17813
0
    if (node == NULL)
17814
0
        return;
17815
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17816
0
    node->Size = node->SizeRef = size;
17817
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17818
0
}
17819
17820
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
17821
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
17822
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
17823
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
17824
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
17825
// - Use (id == 0) to let the system allocate a node identifier.
17826
// - Existing node with a same id will be removed.
17827
ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
17828
0
{
17829
0
    ImGuiContext* ctx = GImGui;
17830
0
    ImGuiContext& g = *ctx; IM_UNUSED(g);
17831
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
17832
17833
0
    if (node_id != 0)
17834
0
        DockBuilderRemoveNode(node_id);
17835
17836
0
    ImGuiDockNode* node = NULL;
17837
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
17838
0
    {
17839
0
        DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
17840
0
        node = DockContextFindNodeByID(ctx, node_id);
17841
0
    }
17842
0
    else
17843
0
    {
17844
0
        node = DockContextAddNode(ctx, node_id);
17845
0
        node->SetLocalFlags(flags);
17846
0
    }
17847
0
    node->LastFrameAlive = ctx->FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
17848
0
    return node->ID;
17849
0
}
17850
17851
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
17852
0
{
17853
0
    ImGuiContext* ctx = GImGui;
17854
0
    ImGuiContext& g = *ctx; IM_UNUSED(g);
17855
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
17856
17857
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17858
0
    if (node == NULL)
17859
0
        return;
17860
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
17861
0
    DockBuilderRemoveNodeChildNodes(node_id);
17862
    // Node may have moved or deleted if e.g. any merge happened
17863
0
    node = DockContextFindNodeByID(ctx, node_id);
17864
0
    if (node == NULL)
17865
0
        return;
17866
0
    if (node->IsCentralNode() && node->ParentNode)
17867
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17868
0
    DockContextRemoveNode(ctx, node, true);
17869
0
}
17870
17871
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
17872
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
17873
0
{
17874
0
    ImGuiContext* ctx = GImGui;
17875
0
    ImGuiDockContext* dc  = &ctx->DockContext;
17876
17877
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL;
17878
0
    if (root_id && root_node == NULL)
17879
0
        return;
17880
0
    bool has_central_node = false;
17881
17882
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
17883
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
17884
17885
    // Process active windows
17886
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
17887
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
17888
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17889
0
        {
17890
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
17891
0
            if (want_removal)
17892
0
            {
17893
0
                if (node->IsCentralNode())
17894
0
                    has_central_node = true;
17895
0
                if (root_id != 0)
17896
0
                    DockContextQueueNotifyRemovedNode(ctx, node);
17897
0
                if (root_node)
17898
0
                {
17899
0
                    DockNodeMoveWindows(root_node, node);
17900
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
17901
0
                }
17902
0
                nodes_to_remove.push_back(node);
17903
0
            }
17904
0
        }
17905
17906
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
17907
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
17908
0
    if (root_node)
17909
0
    {
17910
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
17911
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
17912
0
    }
17913
17914
    // Apply to settings
17915
0
    for (ImGuiWindowSettings* settings = ctx->SettingsWindows.begin(); settings != NULL; settings = ctx->SettingsWindows.next_chunk(settings))
17916
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
17917
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
17918
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
17919
0
                {
17920
0
                    settings->DockId = root_id;
17921
0
                    break;
17922
0
                }
17923
17924
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
17925
0
    if (nodes_to_remove.Size > 1)
17926
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
17927
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
17928
0
        DockContextRemoveNode(ctx, nodes_to_remove[n], false);
17929
17930
0
    if (root_id == 0)
17931
0
    {
17932
0
        dc->Nodes.Clear();
17933
0
        dc->Requests.clear();
17934
0
    }
17935
0
    else if (has_central_node)
17936
0
    {
17937
0
        root_node->CentralNode = root_node;
17938
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17939
0
    }
17940
0
}
17941
17942
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
17943
0
{
17944
    // Clear references in settings
17945
0
    ImGuiContext* ctx = GImGui;
17946
0
    ImGuiContext& g = *ctx;
17947
0
    if (clear_settings_refs)
17948
0
    {
17949
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
17950
0
        {
17951
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
17952
0
            if (!want_removal && settings->DockId != 0)
17953
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, settings->DockId))
17954
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
17955
0
                        want_removal = true;
17956
0
            if (want_removal)
17957
0
                settings->DockId = 0;
17958
0
        }
17959
0
    }
17960
17961
    // Clear references in windows
17962
0
    for (int n = 0; n < g.Windows.Size; n++)
17963
0
    {
17964
0
        ImGuiWindow* window = g.Windows[n];
17965
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
17966
0
        if (want_removal)
17967
0
        {
17968
0
            const ImGuiID backup_dock_id = window->DockId;
17969
0
            IM_UNUSED(backup_dock_id);
17970
0
            DockContextProcessUndockWindow(ctx, window, clear_settings_refs);
17971
0
            if (!clear_settings_refs)
17972
0
                IM_ASSERT(window->DockId == backup_dock_id);
17973
0
        }
17974
0
    }
17975
0
}
17976
17977
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
17978
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
17979
// FIXME-DOCK: We are not exposing nor using split_outer.
17980
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
17981
0
{
17982
0
    ImGuiContext& g = *GImGui;
17983
0
    IM_ASSERT(split_dir != ImGuiDir_None);
17984
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
17985
17986
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
17987
0
    if (node == NULL)
17988
0
    {
17989
0
        IM_ASSERT(node != NULL);
17990
0
        return 0;
17991
0
    }
17992
17993
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
17994
17995
0
    ImGuiDockRequest req;
17996
0
    req.Type = ImGuiDockRequestType_Split;
17997
0
    req.DockTargetWindow = NULL;
17998
0
    req.DockTargetNode = node;
17999
0
    req.DockPayload = NULL;
18000
0
    req.DockSplitDir = split_dir;
18001
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
18002
0
    req.DockSplitOuter = false;
18003
0
    DockContextProcessDock(&g, &req);
18004
18005
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
18006
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
18007
0
    if (out_id_at_dir)
18008
0
        *out_id_at_dir = id_at_dir;
18009
0
    if (out_id_at_opposite_dir)
18010
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
18011
0
    return id_at_dir;
18012
0
}
18013
18014
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
18015
0
{
18016
0
    ImGuiContext& g = *GImGui;
18017
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
18018
0
    dst_node->SharedFlags = src_node->SharedFlags;
18019
0
    dst_node->LocalFlags = src_node->LocalFlags;
18020
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
18021
0
    dst_node->Pos = src_node->Pos;
18022
0
    dst_node->Size = src_node->Size;
18023
0
    dst_node->SizeRef = src_node->SizeRef;
18024
0
    dst_node->SplitAxis = src_node->SplitAxis;
18025
0
    dst_node->UpdateMergedFlags();
18026
18027
0
    out_node_remap_pairs->push_back(src_node->ID);
18028
0
    out_node_remap_pairs->push_back(dst_node->ID);
18029
18030
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
18031
0
        if (src_node->ChildNodes[child_n])
18032
0
        {
18033
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
18034
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
18035
0
        }
18036
18037
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
18038
0
    return dst_node;
18039
0
}
18040
18041
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
18042
0
{
18043
0
    ImGuiContext* ctx = GImGui;
18044
0
    IM_ASSERT(src_node_id != 0);
18045
0
    IM_ASSERT(dst_node_id != 0);
18046
0
    IM_ASSERT(out_node_remap_pairs != NULL);
18047
18048
0
    DockBuilderRemoveNode(dst_node_id);
18049
18050
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(ctx, src_node_id);
18051
0
    IM_ASSERT(src_node != NULL);
18052
18053
0
    out_node_remap_pairs->clear();
18054
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
18055
18056
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
18057
0
}
18058
18059
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
18060
0
{
18061
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
18062
0
    if (src_window == NULL)
18063
0
        return;
18064
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
18065
0
    {
18066
0
        dst_window->Pos = src_window->Pos;
18067
0
        dst_window->Size = src_window->Size;
18068
0
        dst_window->SizeFull = src_window->SizeFull;
18069
0
        dst_window->Collapsed = src_window->Collapsed;
18070
0
    }
18071
0
    else
18072
0
    {
18073
0
        ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
18074
0
        if (!dst_settings)
18075
0
            dst_settings = CreateNewWindowSettings(dst_name);
18076
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
18077
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
18078
0
        {
18079
0
            dst_settings->ViewportPos = window_pos_2ih;
18080
0
            dst_settings->ViewportId = src_window->ViewportId;
18081
0
            dst_settings->Pos = ImVec2ih(0, 0);
18082
0
        }
18083
0
        else
18084
0
        {
18085
0
            dst_settings->Pos = window_pos_2ih;
18086
0
        }
18087
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
18088
0
        dst_settings->Collapsed = src_window->Collapsed;
18089
0
    }
18090
0
}
18091
18092
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
18093
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
18094
0
{
18095
0
    ImGuiContext& g = *GImGui;
18096
0
    IM_ASSERT(src_dockspace_id != 0);
18097
0
    IM_ASSERT(dst_dockspace_id != 0);
18098
0
    IM_ASSERT(in_window_remap_pairs != NULL);
18099
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
18100
18101
    // Duplicate entire dock
18102
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
18103
    // whereas we could attempt to at least keep them together in a new, same floating node.
18104
0
    ImVector<ImGuiID> node_remap_pairs;
18105
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
18106
18107
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
18108
    // (The windows associated to src_dockspace_id are staying in place)
18109
0
    ImVector<ImGuiID> src_windows;
18110
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
18111
0
    {
18112
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
18113
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
18114
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
18115
0
        src_windows.push_back(src_window_id);
18116
18117
        // Search in the remapping tables
18118
0
        ImGuiID src_dock_id = 0;
18119
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
18120
0
            src_dock_id = src_window->DockId;
18121
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
18122
0
            src_dock_id = src_window_settings->DockId;
18123
0
        ImGuiID dst_dock_id = 0;
18124
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18125
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
18126
0
            {
18127
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18128
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
18129
0
                break;
18130
0
            }
18131
18132
0
        if (dst_dock_id != 0)
18133
0
        {
18134
            // Docked windows gets redocked into the new node hierarchy.
18135
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
18136
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
18137
0
        }
18138
0
        else
18139
0
        {
18140
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
18141
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
18142
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
18143
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
18144
0
        }
18145
0
    }
18146
18147
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
18148
    // Find those windows and move to them to the cloned dock node. This may be optional?
18149
    // Dock those are a second step as undocking would invalidate source dock nodes.
18150
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
18151
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
18152
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18153
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
18154
0
        {
18155
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18156
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
18157
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
18158
0
            {
18159
0
                ImGuiWindow* window = node->Windows[window_n];
18160
0
                if (src_windows.contains(window->ID))
18161
0
                    continue;
18162
18163
                // Docked windows gets redocked into the new node hierarchy.
18164
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
18165
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
18166
0
            }
18167
0
        }
18168
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
18169
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
18170
0
}
18171
18172
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
18173
void ImGui::DockBuilderFinish(ImGuiID root_id)
18174
0
{
18175
0
    ImGuiContext* ctx = GImGui;
18176
    //DockContextRebuild(ctx);
18177
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
18178
0
}
18179
18180
//-----------------------------------------------------------------------------
18181
// Docking: Begin/End Support Functions (called from Begin/End)
18182
//-----------------------------------------------------------------------------
18183
// - GetWindowAlwaysWantOwnTabBar()
18184
// - DockContextBindNodeToWindow()
18185
// - BeginDocked()
18186
// - BeginDockableDragDropSource()
18187
// - BeginDockableDragDropTarget()
18188
//-----------------------------------------------------------------------------
18189
18190
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
18191
107k
{
18192
107k
    ImGuiContext& g = *GImGui;
18193
107k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
18194
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
18195
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
18196
0
                return true;
18197
107k
    return false;
18198
107k
}
18199
18200
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
18201
0
{
18202
0
    ImGuiContext& g = *ctx;
18203
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
18204
0
    IM_ASSERT(window->DockNode == NULL);
18205
18206
    // We should not be docking into a split node (SetWindowDock should avoid this)
18207
0
    if (node && node->IsSplitNode())
18208
0
    {
18209
0
        DockContextProcessUndockWindow(ctx, window);
18210
0
        return NULL;
18211
0
    }
18212
18213
    // Create node
18214
0
    if (node == NULL)
18215
0
    {
18216
0
        node = DockContextAddNode(ctx, window->DockId);
18217
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
18218
0
        node->LastFrameAlive = g.FrameCount;
18219
0
    }
18220
18221
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
18222
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
18223
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
18224
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
18225
0
    if (!node->IsVisible)
18226
0
    {
18227
0
        ImGuiDockNode* ancestor_node = node;
18228
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
18229
0
            ancestor_node = ancestor_node->ParentNode;
18230
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
18231
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
18232
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
18233
0
    }
18234
18235
    // Add window to node
18236
0
    bool node_was_visible = node->IsVisible;
18237
0
    DockNodeAddWindow(node, window, true);
18238
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
18239
0
    IM_ASSERT(node == window->DockNode);
18240
0
    return node;
18241
0
}
18242
18243
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
18244
0
{
18245
0
    ImGuiContext* ctx = GImGui;
18246
0
    ImGuiContext& g = *ctx;
18247
18248
    // Clear fields ahead so most early-out paths don't have to do it
18249
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
18250
18251
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
18252
0
    if (auto_dock_node)
18253
0
    {
18254
0
        if (window->DockId == 0)
18255
0
        {
18256
0
            IM_ASSERT(window->DockNode == NULL);
18257
0
            window->DockId = DockContextGenNodeID(ctx);
18258
0
        }
18259
0
    }
18260
0
    else
18261
0
    {
18262
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
18263
0
        bool want_undock = false;
18264
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
18265
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
18266
0
        if (want_undock)
18267
0
        {
18268
0
            DockContextProcessUndockWindow(ctx, window);
18269
0
            return;
18270
0
        }
18271
0
    }
18272
18273
    // Bind to our dock node
18274
0
    ImGuiDockNode* node = window->DockNode;
18275
0
    if (node != NULL)
18276
0
        IM_ASSERT(window->DockId == node->ID);
18277
0
    if (window->DockId != 0 && node == NULL)
18278
0
    {
18279
0
        node = DockContextBindNodeToWindow(ctx, window);
18280
0
        if (node == NULL)
18281
0
            return;
18282
0
    }
18283
18284
#if 0
18285
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
18286
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
18287
    {
18288
        DockContextProcessUndockWindow(ctx, window);
18289
        return;
18290
    }
18291
#endif
18292
18293
    // Undock if our dockspace node disappeared
18294
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
18295
0
    if (node->LastFrameAlive < g.FrameCount)
18296
0
    {
18297
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
18298
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
18299
0
        if (root_node->LastFrameAlive < g.FrameCount)
18300
0
            DockContextProcessUndockWindow(ctx, window);
18301
0
        else
18302
0
            window->DockIsActive = true;
18303
0
        return;
18304
0
    }
18305
18306
    // Store style overrides
18307
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18308
0
        window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18309
18310
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
18311
    // and never create neither a host window neither a tab bar.
18312
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
18313
0
    if (node->HostWindow == NULL)
18314
0
    {
18315
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
18316
0
            window->DockIsActive = true;
18317
0
        if (node->Windows.Size > 1)
18318
0
            DockNodeHideWindowDuringHostWindowCreation(window);
18319
0
        return;
18320
0
    }
18321
18322
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
18323
0
    IM_ASSERT(node->HostWindow);
18324
0
    IM_ASSERT(node->IsLeafNode());
18325
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
18326
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
18327
18328
    // Undock if we are submitted earlier than the host window
18329
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
18330
0
    {
18331
0
        DockContextProcessUndockWindow(ctx, window);
18332
0
        return;
18333
0
    }
18334
18335
    // Position/Size window
18336
0
    SetNextWindowPos(node->Pos);
18337
0
    SetNextWindowSize(node->Size);
18338
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
18339
0
    window->DockIsActive = true;
18340
0
    window->DockNodeIsVisible = true;
18341
0
    window->DockTabIsVisible = false;
18342
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
18343
0
        return;
18344
18345
    // When the window is selected we mark it as visible.
18346
0
    if (node->VisibleWindow == window)
18347
0
        window->DockTabIsVisible = true;
18348
18349
    // Update window flag
18350
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
18351
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize;
18352
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
18353
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
18354
0
    else
18355
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
18356
18357
    // Save new dock order only if the window has been visible once already
18358
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
18359
0
    if (node->TabBar && window->WasActive)
18360
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
18361
18362
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
18363
0
        *p_open = false;
18364
18365
    // Update ChildId to allow returning from Child to Parent with Escape
18366
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
18367
0
    window->ChildId = parent_window->GetID(window->Name);
18368
0
}
18369
18370
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
18371
18
{
18372
18
    ImGuiContext& g = *GImGui;
18373
18
    IM_ASSERT(g.ActiveId == window->MoveId);
18374
18
    IM_ASSERT(g.MovingWindow == window);
18375
18
    IM_ASSERT(g.CurrentWindow == window);
18376
18377
18
    g.LastItemData.ID = window->MoveId;
18378
18
    window = window->RootWindowDockTree;
18379
18
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18380
18
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
18381
18
    if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
18382
18
    {
18383
18
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
18384
18
        EndDragDropSource();
18385
18386
        // Store style overrides
18387
126
        for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18388
108
            window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18389
18
    }
18390
18
}
18391
18392
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
18393
27
{
18394
27
    ImGuiContext* ctx = GImGui;
18395
27
    ImGuiContext& g = *ctx;
18396
18397
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
18398
27
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18399
27
    if (!g.DragDropActive)
18400
0
        return;
18401
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
18402
27
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
18403
27
        return;
18404
18405
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
18406
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
18407
0
    const ImGuiPayload* payload = &g.DragDropPayload;
18408
0
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
18409
0
    {
18410
0
        EndDragDropTarget();
18411
0
        return;
18412
0
    }
18413
18414
0
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
18415
0
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
18416
0
    {
18417
        // Select target node
18418
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
18419
0
        bool dock_into_floating_window = false;
18420
0
        ImGuiDockNode* node = NULL;
18421
0
        if (window->DockNodeAsHost)
18422
0
        {
18423
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
18424
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
18425
18426
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
18427
            // In this case we need to fallback into any leaf mode, possibly the central node.
18428
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
18429
0
            if (node && node->IsDockSpace() && node->IsRootNode())
18430
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
18431
0
        }
18432
0
        else
18433
0
        {
18434
0
            if (window->DockNode)
18435
0
                node = window->DockNode;
18436
0
            else
18437
0
                dock_into_floating_window = true; // Dock into a regular window
18438
0
        }
18439
18440
0
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
18441
0
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
18442
18443
        // Preview docking request and find out split direction/ratio
18444
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
18445
0
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
18446
0
        if (do_preview && (node != NULL || dock_into_floating_window))
18447
0
        {
18448
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
18449
0
            ImGuiDockPreviewData split_inner;
18450
0
            ImGuiDockPreviewData split_outer;
18451
0
            ImGuiDockPreviewData* split_data = &split_inner;
18452
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
18453
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
18454
0
                {
18455
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
18456
0
                    if (split_outer.IsSplitDirExplicit)
18457
0
                        split_data = &split_outer;
18458
0
                }
18459
0
            if (!node || node->IsLeafNode())
18460
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
18461
0
            if (split_data == &split_outer)
18462
0
                split_inner.IsDropAllowed = false;
18463
18464
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
18465
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
18466
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
18467
18468
            // Queue docking request
18469
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
18470
0
                DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
18471
0
        }
18472
0
    }
18473
0
    EndDragDropTarget();
18474
0
}
18475
18476
//-----------------------------------------------------------------------------
18477
// Docking: Settings
18478
//-----------------------------------------------------------------------------
18479
// - DockSettingsRenameNodeReferences()
18480
// - DockSettingsRemoveNodeReferences()
18481
// - DockSettingsFindNodeSettings()
18482
// - DockSettingsHandler_ApplyAll()
18483
// - DockSettingsHandler_ReadOpen()
18484
// - DockSettingsHandler_ReadLine()
18485
// - DockSettingsHandler_DockNodeToSettings()
18486
// - DockSettingsHandler_WriteAll()
18487
//-----------------------------------------------------------------------------
18488
18489
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
18490
0
{
18491
0
    ImGuiContext& g = *GImGui;
18492
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
18493
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
18494
0
    {
18495
0
        ImGuiWindow* window = g.Windows[window_n];
18496
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
18497
0
            window->DockId = new_node_id;
18498
0
    }
18499
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18500
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18501
0
        if (settings->DockId == old_node_id)
18502
0
            settings->DockId = new_node_id;
18503
0
}
18504
18505
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
18506
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
18507
0
{
18508
0
    ImGuiContext& g = *GImGui;
18509
0
    int found = 0;
18510
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18511
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18512
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
18513
0
            if (settings->DockId == node_ids[node_n])
18514
0
            {
18515
0
                settings->DockId = 0;
18516
0
                settings->DockOrder = -1;
18517
0
                if (++found < node_ids_count)
18518
0
                    break;
18519
0
                return;
18520
0
            }
18521
0
}
18522
18523
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
18524
0
{
18525
    // FIXME-OPT
18526
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18527
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
18528
0
        if (dc->NodesSettings[n].ID == id)
18529
0
            return &dc->NodesSettings[n];
18530
0
    return NULL;
18531
0
}
18532
18533
// Clear settings data
18534
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18535
0
{
18536
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18537
0
    dc->NodesSettings.clear();
18538
0
    DockContextClearNodes(ctx, 0, true);
18539
0
}
18540
18541
// Recreate nodes based on settings data
18542
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18543
0
{
18544
    // Prune settings at boot time only
18545
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18546
0
    if (ctx->Windows.Size == 0)
18547
0
        DockContextPruneUnusedSettingsNodes(ctx);
18548
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
18549
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
18550
0
}
18551
18552
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
18553
0
{
18554
0
    if (strcmp(name, "Data") != 0)
18555
0
        return NULL;
18556
0
    return (void*)1;
18557
0
}
18558
18559
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
18560
0
{
18561
0
    char c = 0;
18562
0
    int x = 0, y = 0;
18563
0
    int r = 0;
18564
18565
    // Parsing, e.g.
18566
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
18567
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
18568
    // Important: this code expect currently fields in a fixed order.
18569
0
    ImGuiDockNodeSettings node;
18570
0
    line = ImStrSkipBlank(line);
18571
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
18572
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
18573
0
    else return;
18574
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
18575
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
18576
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
18577
0
    if (node.ParentNodeId == 0)
18578
0
    {
18579
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
18580
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
18581
0
    }
18582
0
    else
18583
0
    {
18584
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
18585
0
    }
18586
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
18587
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
18588
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
18589
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
18590
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
18591
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
18592
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
18593
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
18594
0
    if (node.ParentNodeId != 0)
18595
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
18596
0
            node.Depth = parent_settings->Depth + 1;
18597
0
    ctx->DockContext.NodesSettings.push_back(node);
18598
0
}
18599
18600
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
18601
0
{
18602
0
    ImGuiDockNodeSettings node_settings;
18603
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
18604
0
    node_settings.ID = node->ID;
18605
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
18606
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
18607
0
    node_settings.SelectedTabId = node->SelectedTabId;
18608
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
18609
0
    node_settings.Depth = (char)depth;
18610
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
18611
0
    node_settings.Pos = ImVec2ih(node->Pos);
18612
0
    node_settings.Size = ImVec2ih(node->Size);
18613
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
18614
0
    dc->NodesSettings.push_back(node_settings);
18615
0
    if (node->ChildNodes[0])
18616
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
18617
0
    if (node->ChildNodes[1])
18618
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
18619
0
}
18620
18621
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
18622
0
{
18623
0
    ImGuiContext& g = *ctx;
18624
0
    ImGuiDockContext* dc = &ctx->DockContext;
18625
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18626
0
        return;
18627
18628
    // Gather settings data
18629
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
18630
0
    dc->NodesSettings.resize(0);
18631
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
18632
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18633
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18634
0
            if (node->IsRootNode())
18635
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
18636
18637
0
    int max_depth = 0;
18638
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18639
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
18640
18641
    // Write to text buffer
18642
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
18643
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18644
0
    {
18645
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
18646
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
18647
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
18648
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
18649
0
        if (node_settings->ParentNodeId)
18650
0
        {
18651
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
18652
0
        }
18653
0
        else
18654
0
        {
18655
0
            if (node_settings->ParentWindowId)
18656
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
18657
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
18658
0
        }
18659
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
18660
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
18661
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
18662
0
            buf->appendf(" NoResize=1");
18663
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
18664
0
            buf->appendf(" CentralNode=1");
18665
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
18666
0
            buf->appendf(" NoTabBar=1");
18667
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
18668
0
            buf->appendf(" HiddenTabBar=1");
18669
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
18670
0
            buf->appendf(" NoWindowMenuButton=1");
18671
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
18672
0
            buf->appendf(" NoCloseButton=1");
18673
0
        if (node_settings->SelectedTabId)
18674
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
18675
18676
        // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
18677
0
        if (g.IO.ConfigDebugIniSettings)
18678
0
            if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
18679
0
            {
18680
0
                buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
18681
0
                if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
18682
0
                    buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
18683
                // Iterate settings so we can give info about windows that didn't exist during the session.
18684
0
                int contains_window = 0;
18685
0
                for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18686
0
                    if (settings->DockId == node_settings->ID)
18687
0
                    {
18688
0
                        if (contains_window++ == 0)
18689
0
                            buf->appendf(" ; contains ");
18690
0
                        buf->appendf("'%s' ", settings->GetName());
18691
0
                    }
18692
0
            }
18693
18694
0
        buf->appendf("\n");
18695
0
    }
18696
0
    buf->appendf("\n");
18697
0
}
18698
18699
18700
//-----------------------------------------------------------------------------
18701
// [SECTION] PLATFORM DEPENDENT HELPERS
18702
//-----------------------------------------------------------------------------
18703
18704
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
18705
18706
#ifdef _MSC_VER
18707
#pragma comment(lib, "user32")
18708
#pragma comment(lib, "kernel32")
18709
#endif
18710
18711
// Win32 clipboard implementation
18712
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
18713
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
18714
{
18715
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18716
    g.ClipboardHandlerData.clear();
18717
    if (!::OpenClipboard(NULL))
18718
        return NULL;
18719
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
18720
    if (wbuf_handle == NULL)
18721
    {
18722
        ::CloseClipboard();
18723
        return NULL;
18724
    }
18725
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
18726
    {
18727
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
18728
        g.ClipboardHandlerData.resize(buf_len);
18729
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
18730
    }
18731
    ::GlobalUnlock(wbuf_handle);
18732
    ::CloseClipboard();
18733
    return g.ClipboardHandlerData.Data;
18734
}
18735
18736
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18737
{
18738
    if (!::OpenClipboard(NULL))
18739
        return;
18740
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
18741
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
18742
    if (wbuf_handle == NULL)
18743
    {
18744
        ::CloseClipboard();
18745
        return;
18746
    }
18747
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
18748
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
18749
    ::GlobalUnlock(wbuf_handle);
18750
    ::EmptyClipboard();
18751
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
18752
        ::GlobalFree(wbuf_handle);
18753
    ::CloseClipboard();
18754
}
18755
18756
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
18757
18758
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
18759
static PasteboardRef main_clipboard = 0;
18760
18761
// OSX clipboard implementation
18762
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
18763
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18764
{
18765
    if (!main_clipboard)
18766
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
18767
    PasteboardClear(main_clipboard);
18768
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
18769
    if (cf_data)
18770
    {
18771
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
18772
        CFRelease(cf_data);
18773
    }
18774
}
18775
18776
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
18777
{
18778
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18779
    if (!main_clipboard)
18780
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
18781
    PasteboardSynchronize(main_clipboard);
18782
18783
    ItemCount item_count = 0;
18784
    PasteboardGetItemCount(main_clipboard, &item_count);
18785
    for (ItemCount i = 0; i < item_count; i++)
18786
    {
18787
        PasteboardItemID item_id = 0;
18788
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
18789
        CFArrayRef flavor_type_array = 0;
18790
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
18791
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
18792
        {
18793
            CFDataRef cf_data;
18794
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
18795
            {
18796
                g.ClipboardHandlerData.clear();
18797
                int length = (int)CFDataGetLength(cf_data);
18798
                g.ClipboardHandlerData.resize(length + 1);
18799
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
18800
                g.ClipboardHandlerData[length] = 0;
18801
                CFRelease(cf_data);
18802
                return g.ClipboardHandlerData.Data;
18803
            }
18804
        }
18805
    }
18806
    return NULL;
18807
}
18808
18809
#else
18810
18811
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
18812
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
18813
0
{
18814
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18815
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
18816
0
}
18817
18818
static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
18819
0
{
18820
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18821
0
    g.ClipboardHandlerData.clear();
18822
0
    const char* text_end = text + strlen(text);
18823
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
18824
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
18825
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
18826
0
}
18827
18828
#endif
18829
18830
// Win32 API IME support (for Asian languages, etc.)
18831
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
18832
18833
#include <imm.h>
18834
#ifdef _MSC_VER
18835
#pragma comment(lib, "imm32")
18836
#endif
18837
18838
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
18839
{
18840
    // Notify OS Input Method Editor of text input position
18841
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
18842
    if (hwnd == 0)
18843
        return;
18844
18845
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
18846
    if (HIMC himc = ::ImmGetContext(hwnd))
18847
    {
18848
        COMPOSITIONFORM composition_form = {};
18849
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
18850
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
18851
        composition_form.dwStyle = CFS_FORCE_POSITION;
18852
        ::ImmSetCompositionWindow(himc, &composition_form);
18853
        CANDIDATEFORM candidate_form = {};
18854
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
18855
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
18856
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
18857
        ::ImmSetCandidateWindow(himc, &candidate_form);
18858
        ::ImmReleaseContext(hwnd, himc);
18859
    }
18860
}
18861
18862
#else
18863
18864
0
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
18865
18866
#endif
18867
18868
//-----------------------------------------------------------------------------
18869
// [SECTION] METRICS/DEBUGGER WINDOW
18870
//-----------------------------------------------------------------------------
18871
// - RenderViewportThumbnail() [Internal]
18872
// - RenderViewportsThumbnails() [Internal]
18873
// - DebugTextEncoding()
18874
// - MetricsHelpMarker() [Internal]
18875
// - ShowFontAtlas() [Internal]
18876
// - ShowMetricsWindow()
18877
// - DebugNodeColumns() [Internal]
18878
// - DebugNodeDockNode() [Internal]
18879
// - DebugNodeDrawList() [Internal]
18880
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
18881
// - DebugNodeFont() [Internal]
18882
// - DebugNodeFontGlyph() [Internal]
18883
// - DebugNodeStorage() [Internal]
18884
// - DebugNodeTabBar() [Internal]
18885
// - DebugNodeViewport() [Internal]
18886
// - DebugNodeWindow() [Internal]
18887
// - DebugNodeWindowSettings() [Internal]
18888
// - DebugNodeWindowsList() [Internal]
18889
// - DebugNodeWindowsListByBeginStackParent() [Internal]
18890
//-----------------------------------------------------------------------------
18891
18892
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
18893
18894
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
18895
0
{
18896
0
    ImGuiContext& g = *GImGui;
18897
0
    ImGuiWindow* window = g.CurrentWindow;
18898
18899
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
18900
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
18901
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
18902
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
18903
0
    for (int i = 0; i != g.Windows.Size; i++)
18904
0
    {
18905
0
        ImGuiWindow* thumb_window = g.Windows[i];
18906
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
18907
0
            continue;
18908
0
        if (thumb_window->Viewport != viewport)
18909
0
            continue;
18910
18911
0
        ImRect thumb_r = thumb_window->Rect();
18912
0
        ImRect title_r = thumb_window->TitleBarRect();
18913
0
        thumb_r = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off +  thumb_r.Max * scale));
18914
0
        title_r = ImRect(ImFloor(off + title_r.Min * scale), ImFloor(off +  ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
18915
0
        thumb_r.ClipWithFull(bb);
18916
0
        title_r.ClipWithFull(bb);
18917
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
18918
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
18919
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
18920
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
18921
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
18922
0
    }
18923
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
18924
0
}
18925
18926
static void RenderViewportsThumbnails()
18927
0
{
18928
0
    ImGuiContext& g = *GImGui;
18929
0
    ImGuiWindow* window = g.CurrentWindow;
18930
18931
    // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
18932
0
    float SCALE = 1.0f / 8.0f;
18933
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
18934
0
    for (int n = 0; n < g.Viewports.Size; n++)
18935
0
        bb_full.Add(g.Viewports[n]->GetMainRect());
18936
0
    ImVec2 p = window->DC.CursorPos;
18937
0
    ImVec2 off = p - bb_full.Min * SCALE;
18938
0
    for (int n = 0; n < g.Viewports.Size; n++)
18939
0
    {
18940
0
        ImGuiViewportP* viewport = g.Viewports[n];
18941
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
18942
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
18943
0
    }
18944
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
18945
0
}
18946
18947
static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
18948
0
{
18949
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
18950
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
18951
0
    return b->LastFocusedStampCount - a->LastFocusedStampCount;
18952
0
}
18953
18954
// Draw an arbitrary US keyboard layout to visualize translated keys
18955
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
18956
0
{
18957
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f);
18958
0
    const float  key_rounding = 3.0f;
18959
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f);
18960
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f);
18961
0
    const float  key_face_rounding = 2.0f;
18962
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f);
18963
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
18964
0
    const float  key_row_offset = 9.0f;
18965
18966
0
    ImVec2 board_min = GetCursorScreenPos();
18967
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
18968
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
18969
18970
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
18971
0
    const KeyLayoutData keys_to_display[] =
18972
0
    {
18973
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
18974
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
18975
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
18976
0
    };
18977
18978
    // Elements rendered manually via ImDrawList API are not clipped automatically.
18979
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
18980
0
    Dummy(board_max - board_min);
18981
0
    if (!IsItemVisible())
18982
0
        return;
18983
0
    draw_list->PushClipRect(board_min, board_max, true);
18984
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
18985
0
    {
18986
0
        const KeyLayoutData* key_data = &keys_to_display[n];
18987
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
18988
0
        ImVec2 key_max = key_min + key_size;
18989
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
18990
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
18991
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
18992
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
18993
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
18994
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
18995
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
18996
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
18997
0
        if (IsKeyDown(key_data->Key))
18998
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
18999
0
    }
19000
0
    draw_list->PopClipRect();
19001
0
}
19002
19003
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
19004
void ImGui::DebugTextEncoding(const char* str)
19005
0
{
19006
0
    Text("Text: \"%s\"", str);
19007
0
    if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
19008
0
        return;
19009
0
    TableSetupColumn("Offset");
19010
0
    TableSetupColumn("UTF-8");
19011
0
    TableSetupColumn("Glyph");
19012
0
    TableSetupColumn("Codepoint");
19013
0
    TableHeadersRow();
19014
0
    for (const char* p = str; *p != 0; )
19015
0
    {
19016
0
        unsigned int c;
19017
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
19018
0
        TableNextColumn();
19019
0
        Text("%d", (int)(p - str));
19020
0
        TableNextColumn();
19021
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
19022
0
        {
19023
0
            if (byte_index > 0)
19024
0
                SameLine();
19025
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
19026
0
        }
19027
0
        TableNextColumn();
19028
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
19029
0
            TextUnformatted(p, p + c_utf8_len);
19030
0
        else
19031
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
19032
0
        TableNextColumn();
19033
0
        Text("U+%04X", (int)c);
19034
0
        p += c_utf8_len;
19035
0
    }
19036
0
    EndTable();
19037
0
}
19038
19039
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
19040
static void MetricsHelpMarker(const char* desc)
19041
0
{
19042
0
    ImGui::TextDisabled("(?)");
19043
0
    if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort) && ImGui::BeginTooltip())
19044
0
    {
19045
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
19046
0
        ImGui::TextUnformatted(desc);
19047
0
        ImGui::PopTextWrapPos();
19048
0
        ImGui::EndTooltip();
19049
0
    }
19050
0
}
19051
19052
// [DEBUG] List fonts in a font atlas and display its texture
19053
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
19054
0
{
19055
0
    for (int i = 0; i < atlas->Fonts.Size; i++)
19056
0
    {
19057
0
        ImFont* font = atlas->Fonts[i];
19058
0
        PushID(font);
19059
0
        DebugNodeFont(font);
19060
0
        PopID();
19061
0
    }
19062
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
19063
0
    {
19064
0
        ImGuiContext& g = *GImGui;
19065
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19066
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
19067
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
19068
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
19069
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
19070
0
        TreePop();
19071
0
    }
19072
0
}
19073
19074
void ImGui::ShowMetricsWindow(bool* p_open)
19075
0
{
19076
0
    ImGuiContext& g = *GImGui;
19077
0
    ImGuiIO& io = g.IO;
19078
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19079
0
    if (cfg->ShowDebugLog)
19080
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
19081
0
    if (cfg->ShowStackTool)
19082
0
        ShowStackToolWindow(&cfg->ShowStackTool);
19083
19084
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
19085
0
    {
19086
0
        End();
19087
0
        return;
19088
0
    }
19089
19090
    // Basic info
19091
0
    Text("Dear ImGui %s", GetVersion());
19092
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
19093
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
19094
0
    Text("%d visible windows, %d active allocations", io.MetricsRenderWindows, io.MetricsActiveAllocations);
19095
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
19096
19097
0
    Separator();
19098
19099
    // Debugging enums
19100
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
19101
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
19102
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
19103
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
19104
0
    if (cfg->ShowWindowsRectsType < 0)
19105
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
19106
0
    if (cfg->ShowTablesRectsType < 0)
19107
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
19108
19109
0
    struct Funcs
19110
0
    {
19111
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
19112
0
        {
19113
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
19114
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
19115
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
19116
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
19117
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
19118
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
19119
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
19120
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
19121
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
19122
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
19123
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); } // Note: y1/y2 not always accurate
19124
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); }
19125
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
19126
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
19127
0
            IM_ASSERT(0);
19128
0
            return ImRect();
19129
0
        }
19130
19131
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
19132
0
        {
19133
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
19134
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
19135
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
19136
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
19137
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
19138
0
            else if (rect_type == WRT_Content)       { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
19139
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
19140
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
19141
0
            IM_ASSERT(0);
19142
0
            return ImRect();
19143
0
        }
19144
0
    };
19145
19146
    // Tools
19147
0
    if (TreeNode("Tools"))
19148
0
    {
19149
0
        bool show_encoding_viewer = TreeNode("UTF-8 Encoding viewer");
19150
0
        SameLine();
19151
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
19152
0
        if (show_encoding_viewer)
19153
0
        {
19154
0
            static char buf[100] = "";
19155
0
            SetNextItemWidth(-FLT_MIN);
19156
0
            InputText("##Text", buf, IM_ARRAYSIZE(buf));
19157
0
            if (buf[0] != 0)
19158
0
                DebugTextEncoding(buf);
19159
0
            TreePop();
19160
0
        }
19161
19162
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
19163
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
19164
0
            DebugStartItemPicker();
19165
0
        SameLine();
19166
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
19167
19168
        // Stack Tool is your best friend!
19169
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
19170
0
        SameLine();
19171
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
19172
19173
        // Stack Tool is your best friend!
19174
0
        Checkbox("Show Stack Tool", &cfg->ShowStackTool);
19175
0
        SameLine();
19176
0
        MetricsHelpMarker("You can also call ImGui::ShowStackToolWindow() from your code.");
19177
19178
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
19179
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
19180
0
        SameLine();
19181
0
        SetNextItemWidth(GetFontSize() * 12);
19182
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
19183
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
19184
0
        {
19185
0
            BulletText("'%s':", g.NavWindow->Name);
19186
0
            Indent();
19187
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
19188
0
            {
19189
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
19190
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
19191
0
            }
19192
0
            Unindent();
19193
0
        }
19194
19195
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
19196
0
        SameLine();
19197
0
        SetNextItemWidth(GetFontSize() * 12);
19198
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
19199
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
19200
0
        {
19201
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19202
0
            {
19203
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19204
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
19205
0
                    continue;
19206
19207
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
19208
0
                if (IsItemHovered())
19209
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19210
0
                Indent();
19211
0
                char buf[128];
19212
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
19213
0
                {
19214
0
                    if (rect_n >= TRT_ColumnsRect)
19215
0
                    {
19216
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
19217
0
                            continue;
19218
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19219
0
                        {
19220
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
19221
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
19222
0
                            Selectable(buf);
19223
0
                            if (IsItemHovered())
19224
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19225
0
                        }
19226
0
                    }
19227
0
                    else
19228
0
                    {
19229
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
19230
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
19231
0
                        Selectable(buf);
19232
0
                        if (IsItemHovered())
19233
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19234
0
                    }
19235
0
                }
19236
0
                Unindent();
19237
0
            }
19238
0
        }
19239
19240
0
        Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
19241
0
        SameLine();
19242
0
        MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
19243
19244
0
        TreePop();
19245
0
    }
19246
19247
    // Windows
19248
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
19249
0
    {
19250
        //SetNextItemOpen(true, ImGuiCond_Once);
19251
0
        DebugNodeWindowsList(&g.Windows, "By display order");
19252
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
19253
0
        if (TreeNode("By submission order (begin stack)"))
19254
0
        {
19255
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
19256
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
19257
0
            temp_buffer.resize(0);
19258
0
            for (int i = 0; i < g.Windows.Size; i++)
19259
0
                if (g.Windows[i]->LastFrameActive + 1 >= g.FrameCount)
19260
0
                    temp_buffer.push_back(g.Windows[i]);
19261
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
19262
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
19263
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
19264
0
            TreePop();
19265
0
        }
19266
19267
0
        TreePop();
19268
0
    }
19269
19270
    // DrawLists
19271
0
    int drawlist_count = 0;
19272
0
    for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
19273
0
        drawlist_count += g.Viewports[viewport_i]->DrawDataBuilder.GetDrawListCount();
19274
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
19275
0
    {
19276
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
19277
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
19278
0
        for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
19279
0
        {
19280
0
            ImGuiViewportP* viewport = g.Viewports[viewport_i];
19281
0
            bool viewport_has_drawlist = false;
19282
0
            for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
19283
0
                for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
19284
0
                {
19285
0
                    if (!viewport_has_drawlist)
19286
0
                        Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
19287
0
                    viewport_has_drawlist = true;
19288
0
                    DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
19289
0
                }
19290
0
        }
19291
0
        TreePop();
19292
0
    }
19293
19294
    // Viewports
19295
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
19296
0
    {
19297
0
        Indent(GetTreeNodeToLabelSpacing());
19298
0
        RenderViewportsThumbnails();
19299
0
        Unindent(GetTreeNodeToLabelSpacing());
19300
19301
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
19302
0
        SameLine();
19303
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
19304
0
        if (open)
19305
0
        {
19306
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
19307
0
            {
19308
0
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
19309
0
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
19310
0
                    i, mon.DpiScale * 100.0f,
19311
0
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
19312
0
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
19313
0
            }
19314
0
            TreePop();
19315
0
        }
19316
19317
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
19318
0
        if (TreeNode("Inferred Z order (front-to-back)"))
19319
0
        {
19320
0
            static ImVector<ImGuiViewportP*> viewports;
19321
0
            viewports.resize(g.Viewports.Size);
19322
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
19323
0
            if (viewports.Size > 1)
19324
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
19325
0
            for (ImGuiViewportP* viewport : viewports)
19326
0
                BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
19327
0
                    viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
19328
0
                    (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
19329
0
                    viewport->Window ? viewport->Window->Name : "N/A");
19330
0
            TreePop();
19331
0
        }
19332
0
        for (int i = 0; i < g.Viewports.Size; i++)
19333
0
            DebugNodeViewport(g.Viewports[i]);
19334
0
        TreePop();
19335
0
    }
19336
19337
    // Details for Popups
19338
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
19339
0
    {
19340
0
        for (int i = 0; i < g.OpenPopupStack.Size; i++)
19341
0
        {
19342
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
19343
0
            const ImGuiPopupData* popup_data = &g.OpenPopupStack[i];
19344
0
            ImGuiWindow* window = popup_data->Window;
19345
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), BackupNavWindow '%s', ParentWindow '%s'",
19346
0
                popup_data->PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
19347
0
                popup_data->BackupNavWindow ? popup_data->BackupNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
19348
0
        }
19349
0
        TreePop();
19350
0
    }
19351
19352
    // Details for TabBars
19353
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
19354
0
    {
19355
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
19356
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
19357
0
            {
19358
0
                PushID(tab_bar);
19359
0
                DebugNodeTabBar(tab_bar, "TabBar");
19360
0
                PopID();
19361
0
            }
19362
0
        TreePop();
19363
0
    }
19364
19365
    // Details for Tables
19366
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
19367
0
    {
19368
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
19369
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
19370
0
                DebugNodeTable(table);
19371
0
        TreePop();
19372
0
    }
19373
19374
    // Details for Fonts
19375
0
    ImFontAtlas* atlas = g.IO.Fonts;
19376
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
19377
0
    {
19378
0
        ShowFontAtlas(atlas);
19379
0
        TreePop();
19380
0
    }
19381
19382
    // Details for InputText
19383
0
    if (TreeNode("InputText"))
19384
0
    {
19385
0
        DebugNodeInputTextState(&g.InputTextState);
19386
0
        TreePop();
19387
0
    }
19388
19389
    // Details for Docking
19390
0
#ifdef IMGUI_HAS_DOCK
19391
0
    if (TreeNode("Docking"))
19392
0
    {
19393
0
        static bool root_nodes_only = true;
19394
0
        ImGuiDockContext* dc = &g.DockContext;
19395
0
        Checkbox("List root nodes", &root_nodes_only);
19396
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
19397
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
19398
0
        SameLine();
19399
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
19400
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
19401
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19402
0
                if (!root_nodes_only || node->IsRootNode())
19403
0
                    DebugNodeDockNode(node, "Node");
19404
0
        TreePop();
19405
0
    }
19406
0
#endif // #ifdef IMGUI_HAS_DOCK
19407
19408
    // Settings
19409
0
    if (TreeNode("Settings"))
19410
0
    {
19411
0
        if (SmallButton("Clear"))
19412
0
            ClearIniSettings();
19413
0
        SameLine();
19414
0
        if (SmallButton("Save to memory"))
19415
0
            SaveIniSettingsToMemory();
19416
0
        SameLine();
19417
0
        if (SmallButton("Save to disk"))
19418
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
19419
0
        SameLine();
19420
0
        if (g.IO.IniFilename)
19421
0
            Text("\"%s\"", g.IO.IniFilename);
19422
0
        else
19423
0
            TextUnformatted("<NULL>");
19424
0
        Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
19425
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
19426
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
19427
0
        {
19428
0
            for (int n = 0; n < g.SettingsHandlers.Size; n++)
19429
0
                BulletText("\"%s\"", g.SettingsHandlers[n].TypeName);
19430
0
            TreePop();
19431
0
        }
19432
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
19433
0
        {
19434
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19435
0
                DebugNodeWindowSettings(settings);
19436
0
            TreePop();
19437
0
        }
19438
19439
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
19440
0
        {
19441
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
19442
0
                DebugNodeTableSettings(settings);
19443
0
            TreePop();
19444
0
        }
19445
19446
0
#ifdef IMGUI_HAS_DOCK
19447
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
19448
0
        {
19449
0
            ImGuiDockContext* dc = &g.DockContext;
19450
0
            Text("In SettingsWindows:");
19451
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19452
0
                if (settings->DockId != 0)
19453
0
                    BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
19454
0
            Text("In SettingsNodes:");
19455
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
19456
0
            {
19457
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
19458
0
                const char* selected_tab_name = NULL;
19459
0
                if (settings->SelectedTabId)
19460
0
                {
19461
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
19462
0
                        selected_tab_name = window->Name;
19463
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
19464
0
                        selected_tab_name = window_settings->GetName();
19465
0
                }
19466
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
19467
0
            }
19468
0
            TreePop();
19469
0
        }
19470
0
#endif // #ifdef IMGUI_HAS_DOCK
19471
19472
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
19473
0
        {
19474
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
19475
0
            TreePop();
19476
0
        }
19477
0
        TreePop();
19478
0
    }
19479
19480
0
    if (TreeNode("Inputs"))
19481
0
    {
19482
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
19483
0
        {
19484
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
19485
            // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
19486
0
            Indent();
19487
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
19488
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
19489
#else
19490
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
19491
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
19492
#endif
19493
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
19494
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19495
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19496
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
19497
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
19498
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
19499
0
            Unindent();
19500
0
        }
19501
19502
0
        Text("MOUSE STATE");
19503
0
        {
19504
0
            Indent();
19505
0
            if (IsMousePosValid())
19506
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
19507
0
            else
19508
0
                Text("Mouse pos: <INVALID>");
19509
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
19510
0
            int count = IM_ARRAYSIZE(io.MouseDown);
19511
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
19512
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
19513
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
19514
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
19515
0
            Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
19516
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
19517
0
            Unindent();
19518
0
        }
19519
19520
0
        Text("MOUSE WHEELING");
19521
0
        {
19522
0
            Indent();
19523
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
19524
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
19525
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
19526
0
            Unindent();
19527
0
        }
19528
19529
0
        Text("KEY OWNERS");
19530
0
        {
19531
0
            Indent();
19532
0
            if (BeginListBox("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19533
0
            {
19534
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19535
0
                {
19536
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
19537
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
19538
0
                        continue;
19539
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
19540
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
19541
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
19542
0
                }
19543
0
                EndListBox();
19544
0
            }
19545
0
            Unindent();
19546
0
        }
19547
0
        Text("SHORTCUT ROUTING");
19548
0
        {
19549
0
            Indent();
19550
0
            if (BeginListBox("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19551
0
            {
19552
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19553
0
                {
19554
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
19555
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
19556
0
                    {
19557
0
                        char key_chord_name[64];
19558
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
19559
0
                        GetKeyChordName(key | routing_data->Mods, key_chord_name, IM_ARRAYSIZE(key_chord_name));
19560
0
                        Text("%s: 0x%08X", key_chord_name, routing_data->RoutingCurr);
19561
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
19562
0
                        idx = routing_data->NextEntryIndex;
19563
0
                    }
19564
0
                }
19565
0
                EndListBox();
19566
0
            }
19567
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19568
0
            Unindent();
19569
0
        }
19570
0
        TreePop();
19571
0
    }
19572
19573
0
    if (TreeNode("Internal state"))
19574
0
    {
19575
0
        Text("WINDOWING");
19576
0
        Indent();
19577
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
19578
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
19579
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
19580
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
19581
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
19582
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
19583
0
        Unindent();
19584
19585
0
        Text("ITEMS");
19586
0
        Indent();
19587
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
19588
0
        DebugLocateItemOnHover(g.ActiveId);
19589
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
19590
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19591
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
19592
0
        Text("HoverDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverDelayId, g.HoverDelayTimer, g.HoverDelayClearTimer);
19593
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
19594
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
19595
0
        Unindent();
19596
19597
0
        Text("NAV,FOCUS");
19598
0
        Indent();
19599
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
19600
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
19601
0
        DebugLocateItemOnHover(g.NavId);
19602
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
19603
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
19604
0
        Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
19605
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
19606
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
19607
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
19608
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
19609
0
        Unindent();
19610
19611
0
        TreePop();
19612
0
    }
19613
19614
    // Overlay: Display windows Rectangles and Begin Order
19615
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
19616
0
    {
19617
0
        for (int n = 0; n < g.Windows.Size; n++)
19618
0
        {
19619
0
            ImGuiWindow* window = g.Windows[n];
19620
0
            if (!window->WasActive)
19621
0
                continue;
19622
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
19623
0
            if (cfg->ShowWindowsRects)
19624
0
            {
19625
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
19626
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
19627
0
            }
19628
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
19629
0
            {
19630
0
                char buf[32];
19631
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
19632
0
                float font_size = GetFontSize();
19633
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
19634
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
19635
0
            }
19636
0
        }
19637
0
    }
19638
19639
    // Overlay: Display Tables Rectangles
19640
0
    if (cfg->ShowTablesRects)
19641
0
    {
19642
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19643
0
        {
19644
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19645
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
19646
0
                continue;
19647
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
19648
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
19649
0
            {
19650
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19651
0
                {
19652
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
19653
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
19654
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
19655
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
19656
0
                }
19657
0
            }
19658
0
            else
19659
0
            {
19660
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
19661
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
19662
0
            }
19663
0
        }
19664
0
    }
19665
19666
0
#ifdef IMGUI_HAS_DOCK
19667
    // Overlay: Display Docking info
19668
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
19669
0
    {
19670
0
        char buf[64] = "";
19671
0
        char* p = buf;
19672
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
19673
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
19674
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
19675
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
19676
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
19677
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
19678
0
        int depth = DockNodeGetDepth(node);
19679
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
19680
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
19681
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
19682
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
19683
0
    }
19684
0
#endif // #ifdef IMGUI_HAS_DOCK
19685
19686
0
    End();
19687
0
}
19688
19689
// [DEBUG] Display contents of Columns
19690
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
19691
0
{
19692
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
19693
0
        return;
19694
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
19695
0
    for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
19696
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
19697
0
    TreePop();
19698
0
}
19699
19700
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
19701
0
{
19702
0
    using namespace ImGui;
19703
0
    PushID(label);
19704
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
19705
0
    Text("%s:", label);
19706
0
    if (!enabled)
19707
0
        BeginDisabled();
19708
0
    CheckboxFlags("NoSplit", p_flags, ImGuiDockNodeFlags_NoSplit);
19709
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
19710
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
19711
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
19712
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
19713
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
19714
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
19715
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
19716
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking);
19717
0
    CheckboxFlags("NoDockingSplitMe", p_flags, ImGuiDockNodeFlags_NoDockingSplitMe);
19718
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
19719
0
    CheckboxFlags("NoDockingOverMe", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
19720
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
19721
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
19722
0
    if (!enabled)
19723
0
        EndDisabled();
19724
0
    PopStyleVar();
19725
0
    PopID();
19726
0
}
19727
19728
// [DEBUG] Display contents of ImDockNode
19729
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
19730
0
{
19731
0
    ImGuiContext& g = *GImGui;
19732
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
19733
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
19734
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19735
0
    bool open;
19736
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
19737
0
    if (node->Windows.Size > 0)
19738
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
19739
0
    else
19740
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
19741
0
    if (!is_alive) { PopStyleColor(); }
19742
0
    if (is_active && IsItemHovered())
19743
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
19744
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
19745
0
    if (open)
19746
0
    {
19747
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
19748
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
19749
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
19750
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
19751
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
19752
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
19753
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
19754
0
        BulletText("Misc:%s%s%s%s%s%s%s",
19755
0
            node->IsDockSpace() ? " IsDockSpace" : "",
19756
0
            node->IsCentralNode() ? " IsCentralNode" : "",
19757
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
19758
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
19759
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
19760
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
19761
0
        {
19762
0
            if (BeginTable("flags", 4))
19763
0
            {
19764
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
19765
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
19766
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
19767
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
19768
0
                EndTable();
19769
0
            }
19770
0
            TreePop();
19771
0
        }
19772
0
        if (node->ParentNode)
19773
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
19774
0
        if (node->ChildNodes[0])
19775
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
19776
0
        if (node->ChildNodes[1])
19777
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
19778
0
        if (node->TabBar)
19779
0
            DebugNodeTabBar(node->TabBar, "TabBar");
19780
0
        DebugNodeWindowsList(&node->Windows, "Windows");
19781
19782
0
        TreePop();
19783
0
    }
19784
0
}
19785
19786
// [DEBUG] Display contents of ImDrawList
19787
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
19788
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
19789
0
{
19790
0
    ImGuiContext& g = *GImGui;
19791
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19792
0
    int cmd_count = draw_list->CmdBuffer.Size;
19793
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
19794
0
        cmd_count--;
19795
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
19796
0
    if (draw_list == GetWindowDrawList())
19797
0
    {
19798
0
        SameLine();
19799
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
19800
0
        if (node_open)
19801
0
            TreePop();
19802
0
        return;
19803
0
    }
19804
19805
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
19806
0
    if (window && IsItemHovered() && fg_draw_list)
19807
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19808
0
    if (!node_open)
19809
0
        return;
19810
19811
0
    if (window && !window->WasActive)
19812
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
19813
19814
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
19815
0
    {
19816
0
        if (pcmd->UserCallback)
19817
0
        {
19818
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
19819
0
            continue;
19820
0
        }
19821
19822
0
        char buf[300];
19823
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
19824
0
            pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
19825
0
            pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
19826
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
19827
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
19828
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
19829
0
        if (!pcmd_node_open)
19830
0
            continue;
19831
19832
        // Calculate approximate coverage area (touched pixel count)
19833
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
19834
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
19835
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
19836
0
        float total_area = 0.0f;
19837
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
19838
0
        {
19839
0
            ImVec2 triangle[3];
19840
0
            for (int n = 0; n < 3; n++, idx_n++)
19841
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
19842
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
19843
0
        }
19844
19845
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
19846
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
19847
0
        Selectable(buf);
19848
0
        if (IsItemHovered() && fg_draw_list)
19849
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
19850
19851
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
19852
0
        ImGuiListClipper clipper;
19853
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
19854
0
        while (clipper.Step())
19855
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
19856
0
            {
19857
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
19858
0
                ImVec2 triangle[3];
19859
0
                for (int n = 0; n < 3; n++, idx_i++)
19860
0
                {
19861
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
19862
0
                    triangle[n] = v.pos;
19863
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
19864
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
19865
0
                }
19866
19867
0
                Selectable(buf, false);
19868
0
                if (fg_draw_list && IsItemHovered())
19869
0
                {
19870
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
19871
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
19872
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
19873
0
                    fg_draw_list->Flags = backup_flags;
19874
0
                }
19875
0
            }
19876
0
        TreePop();
19877
0
    }
19878
0
    TreePop();
19879
0
}
19880
19881
// [DEBUG] Display mesh/aabb of a ImDrawCmd
19882
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
19883
0
{
19884
0
    IM_ASSERT(show_mesh || show_aabb);
19885
19886
    // Draw wire-frame version of all triangles
19887
0
    ImRect clip_rect = draw_cmd->ClipRect;
19888
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
19889
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
19890
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
19891
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
19892
0
    {
19893
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
19894
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
19895
19896
0
        ImVec2 triangle[3];
19897
0
        for (int n = 0; n < 3; n++, idx_n++)
19898
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
19899
0
        if (show_mesh)
19900
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
19901
0
    }
19902
    // Draw bounding boxes
19903
0
    if (show_aabb)
19904
0
    {
19905
0
        out_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
19906
0
        out_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
19907
0
    }
19908
0
    out_draw_list->Flags = backup_flags;
19909
0
}
19910
19911
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
19912
void ImGui::DebugNodeFont(ImFont* font)
19913
0
{
19914
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
19915
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
19916
0
    SameLine();
19917
0
    if (SmallButton("Set as default"))
19918
0
        GetIO().FontDefault = font;
19919
0
    if (!opened)
19920
0
        return;
19921
19922
    // Display preview text
19923
0
    PushFont(font);
19924
0
    Text("The quick brown fox jumps over the lazy dog");
19925
0
    PopFont();
19926
19927
    // Display details
19928
0
    SetNextItemWidth(GetFontSize() * 8);
19929
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
19930
0
    SameLine(); MetricsHelpMarker(
19931
0
        "Note than the default embedded font is NOT meant to be scaled.\n\n"
19932
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
19933
0
        "You may oversample them to get some flexibility with scaling. "
19934
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
19935
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
19936
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
19937
0
    char c_str[5];
19938
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
19939
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
19940
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
19941
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
19942
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
19943
0
        if (font->ConfigData)
19944
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
19945
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
19946
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
19947
19948
    // Display all glyphs of the fonts in separate pages of 256 characters
19949
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
19950
0
    {
19951
0
        ImDrawList* draw_list = GetWindowDrawList();
19952
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
19953
0
        const float cell_size = font->FontSize * 1;
19954
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
19955
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
19956
0
        {
19957
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
19958
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
19959
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
19960
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
19961
0
            {
19962
0
                base += 4096 - 256;
19963
0
                continue;
19964
0
            }
19965
19966
0
            int count = 0;
19967
0
            for (unsigned int n = 0; n < 256; n++)
19968
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
19969
0
                    count++;
19970
0
            if (count <= 0)
19971
0
                continue;
19972
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
19973
0
                continue;
19974
19975
            // Draw a 16x16 grid of glyphs
19976
0
            ImVec2 base_pos = GetCursorScreenPos();
19977
0
            for (unsigned int n = 0; n < 256; n++)
19978
0
            {
19979
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
19980
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
19981
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
19982
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
19983
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
19984
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
19985
0
                if (!glyph)
19986
0
                    continue;
19987
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
19988
0
                if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
19989
0
                {
19990
0
                    DebugNodeFontGlyph(font, glyph);
19991
0
                    EndTooltip();
19992
0
                }
19993
0
            }
19994
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
19995
0
            TreePop();
19996
0
        }
19997
0
        TreePop();
19998
0
    }
19999
0
    TreePop();
20000
0
}
20001
20002
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
20003
0
{
20004
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
20005
0
    Separator();
20006
0
    Text("Visible: %d", glyph->Visible);
20007
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
20008
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
20009
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
20010
0
}
20011
20012
// [DEBUG] Display contents of ImGuiStorage
20013
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
20014
0
{
20015
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
20016
0
        return;
20017
0
    for (int n = 0; n < storage->Data.Size; n++)
20018
0
    {
20019
0
        const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
20020
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
20021
0
    }
20022
0
    TreePop();
20023
0
}
20024
20025
// [DEBUG] Display contents of ImGuiTabBar
20026
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
20027
0
{
20028
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
20029
0
    char buf[256];
20030
0
    char* p = buf;
20031
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
20032
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
20033
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s  {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
20034
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
20035
0
    {
20036
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20037
0
        p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
20038
0
    }
20039
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
20040
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20041
0
    bool open = TreeNode(label, "%s", buf);
20042
0
    if (!is_active) { PopStyleColor(); }
20043
0
    if (is_active && IsItemHovered())
20044
0
    {
20045
0
        ImDrawList* draw_list = GetForegroundDrawList();
20046
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
20047
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20048
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20049
0
    }
20050
0
    if (open)
20051
0
    {
20052
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
20053
0
        {
20054
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20055
0
            PushID(tab);
20056
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
20057
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
20058
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
20059
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
20060
0
            PopID();
20061
0
        }
20062
0
        TreePop();
20063
0
    }
20064
0
}
20065
20066
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
20067
0
{
20068
0
    SetNextItemOpen(true, ImGuiCond_Once);
20069
0
    if (TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"))
20070
0
    {
20071
0
        ImGuiWindowFlags flags = viewport->Flags;
20072
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
20073
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
20074
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
20075
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
20076
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
20077
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
20078
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
20079
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
20080
0
            (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
20081
0
            (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
20082
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
20083
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
20084
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
20085
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
20086
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
20087
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
20088
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
20089
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
20090
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
20091
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
20092
0
        for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
20093
0
            for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
20094
0
                DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
20095
0
        TreePop();
20096
0
    }
20097
0
}
20098
20099
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
20100
0
{
20101
0
    if (window == NULL)
20102
0
    {
20103
0
        BulletText("%s: NULL", label);
20104
0
        return;
20105
0
    }
20106
20107
0
    ImGuiContext& g = *GImGui;
20108
0
    const bool is_active = window->WasActive;
20109
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
20110
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20111
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
20112
0
    if (!is_active) { PopStyleColor(); }
20113
0
    if (IsItemHovered() && is_active)
20114
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20115
0
    if (!open)
20116
0
        return;
20117
20118
0
    if (window->MemoryCompacted)
20119
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
20120
20121
0
    ImGuiWindowFlags flags = window->Flags;
20122
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
20123
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
20124
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
20125
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
20126
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
20127
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
20128
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
20129
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
20130
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
20131
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
20132
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
20133
0
    {
20134
0
        ImRect r = window->NavRectRel[layer];
20135
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
20136
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
20137
0
        else
20138
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
20139
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
20140
0
    }
20141
0
    const ImVec2* pr = window->NavPreferredScoringPosRel;
20142
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
20143
0
        BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
20144
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
20145
20146
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
20147
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
20148
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
20149
0
    if (window->DockNode || window->DockNodeAsHost)
20150
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
20151
20152
0
    if (window->RootWindow != window)       { DebugNodeWindow(window->RootWindow, "RootWindow"); }
20153
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
20154
0
    if (window->ParentWindow != NULL)       { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
20155
0
    if (window->DC.ChildWindows.Size > 0)   { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
20156
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
20157
0
    {
20158
0
        for (int n = 0; n < window->ColumnsStorage.Size; n++)
20159
0
            DebugNodeColumns(&window->ColumnsStorage[n]);
20160
0
        TreePop();
20161
0
    }
20162
0
    DebugNodeStorage(&window->StateStorage, "Storage");
20163
0
    TreePop();
20164
0
}
20165
20166
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
20167
0
{
20168
0
    if (settings->WantDelete)
20169
0
        BeginDisabled();
20170
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
20171
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
20172
0
    if (settings->WantDelete)
20173
0
        EndDisabled();
20174
0
}
20175
20176
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
20177
0
{
20178
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
20179
0
        return;
20180
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
20181
0
    {
20182
0
        PushID((*windows)[i]);
20183
0
        DebugNodeWindow((*windows)[i], "Window");
20184
0
        PopID();
20185
0
    }
20186
0
    TreePop();
20187
0
}
20188
20189
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
20190
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
20191
0
{
20192
0
    for (int i = 0; i < windows_size; i++)
20193
0
    {
20194
0
        ImGuiWindow* window = windows[i];
20195
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
20196
0
            continue;
20197
0
        char buf[20];
20198
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
20199
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
20200
0
        DebugNodeWindow(window, buf);
20201
0
        Indent();
20202
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
20203
0
        Unindent();
20204
0
    }
20205
0
}
20206
20207
//-----------------------------------------------------------------------------
20208
// [SECTION] DEBUG LOG WINDOW
20209
//-----------------------------------------------------------------------------
20210
20211
void ImGui::DebugLog(const char* fmt, ...)
20212
0
{
20213
0
    va_list args;
20214
0
    va_start(args, fmt);
20215
0
    DebugLogV(fmt, args);
20216
0
    va_end(args);
20217
0
}
20218
20219
void ImGui::DebugLogV(const char* fmt, va_list args)
20220
0
{
20221
0
    ImGuiContext& g = *GImGui;
20222
0
    const int old_size = g.DebugLogBuf.size();
20223
0
    g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
20224
0
    g.DebugLogBuf.appendfv(fmt, args);
20225
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
20226
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
20227
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
20228
0
}
20229
20230
void ImGui::ShowDebugLogWindow(bool* p_open)
20231
0
{
20232
0
    ImGuiContext& g = *GImGui;
20233
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20234
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
20235
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
20236
0
    {
20237
0
        End();
20238
0
        return;
20239
0
    }
20240
20241
0
    CheckboxFlags("All", &g.DebugLogFlags, ImGuiDebugLogFlags_EventMask_);
20242
0
    SameLine(); CheckboxFlags("ActiveId", &g.DebugLogFlags, ImGuiDebugLogFlags_EventActiveId);
20243
0
    SameLine(); CheckboxFlags("Focus", &g.DebugLogFlags, ImGuiDebugLogFlags_EventFocus);
20244
0
    SameLine(); CheckboxFlags("Popup", &g.DebugLogFlags, ImGuiDebugLogFlags_EventPopup);
20245
0
    SameLine(); CheckboxFlags("Nav", &g.DebugLogFlags, ImGuiDebugLogFlags_EventNav);
20246
0
    SameLine(); if (CheckboxFlags("Clipper", &g.DebugLogFlags, ImGuiDebugLogFlags_EventClipper)) { g.DebugLogClipperAutoDisableFrames = 2; } if (IsItemHovered()) SetTooltip("Clipper log auto-disabled after 2 frames");
20247
    //SameLine(); CheckboxFlags("Selection", &g.DebugLogFlags, ImGuiDebugLogFlags_EventSelection);
20248
0
    SameLine(); CheckboxFlags("IO", &g.DebugLogFlags, ImGuiDebugLogFlags_EventIO);
20249
0
    SameLine(); CheckboxFlags("Docking", &g.DebugLogFlags, ImGuiDebugLogFlags_EventDocking);
20250
0
    SameLine(); CheckboxFlags("Viewport", &g.DebugLogFlags, ImGuiDebugLogFlags_EventViewport);
20251
20252
0
    if (SmallButton("Clear"))
20253
0
    {
20254
0
        g.DebugLogBuf.clear();
20255
0
        g.DebugLogIndex.clear();
20256
0
    }
20257
0
    SameLine();
20258
0
    if (SmallButton("Copy"))
20259
0
        SetClipboardText(g.DebugLogBuf.c_str());
20260
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
20261
20262
0
    ImGuiListClipper clipper;
20263
0
    clipper.Begin(g.DebugLogIndex.size());
20264
0
    while (clipper.Step())
20265
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
20266
0
        {
20267
0
            const char* line_begin = g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no);
20268
0
            const char* line_end = g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no);
20269
0
            TextUnformatted(line_begin, line_end);
20270
0
            ImRect text_rect = g.LastItemData.Rect;
20271
0
            if (IsItemHovered())
20272
0
                for (const char* p = line_begin; p <= line_end - 10; p++)
20273
0
                {
20274
0
                    ImGuiID id = 0;
20275
0
                    if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
20276
0
                        continue;
20277
0
                    ImVec2 p0 = CalcTextSize(line_begin, p);
20278
0
                    ImVec2 p1 = CalcTextSize(p, p + 10);
20279
0
                    g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
20280
0
                    if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
20281
0
                        DebugLocateItemOnHover(id);
20282
0
                    p += 10;
20283
0
                }
20284
0
        }
20285
0
    if (GetScrollY() >= GetScrollMaxY())
20286
0
        SetScrollHereY(1.0f);
20287
0
    EndChild();
20288
20289
0
    End();
20290
0
}
20291
20292
//-----------------------------------------------------------------------------
20293
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
20294
//-----------------------------------------------------------------------------
20295
20296
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
20297
20298
void ImGui::DebugLocateItem(ImGuiID target_id)
20299
0
{
20300
0
    ImGuiContext& g = *GImGui;
20301
0
    g.DebugLocateId = target_id;
20302
0
    g.DebugLocateFrames = 2;
20303
0
}
20304
20305
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
20306
0
{
20307
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
20308
0
        return;
20309
0
    ImGuiContext& g = *GImGui;
20310
0
    DebugLocateItem(target_id);
20311
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
20312
0
}
20313
20314
void ImGui::DebugLocateItemResolveWithLastItem()
20315
0
{
20316
0
    ImGuiContext& g = *GImGui;
20317
0
    ImGuiLastItemData item_data = g.LastItemData;
20318
0
    g.DebugLocateId = 0;
20319
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
20320
0
    ImRect r = item_data.Rect;
20321
0
    r.Expand(3.0f);
20322
0
    ImVec2 p1 = g.IO.MousePos;
20323
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
20324
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
20325
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
20326
0
}
20327
20328
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
20329
void ImGui::UpdateDebugToolItemPicker()
20330
35.9k
{
20331
35.9k
    ImGuiContext& g = *GImGui;
20332
35.9k
    g.DebugItemPickerBreakId = 0;
20333
35.9k
    if (!g.DebugItemPickerActive)
20334
35.9k
        return;
20335
20336
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20337
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
20338
0
    if (IsKeyPressed(ImGuiKey_Escape))
20339
0
        g.DebugItemPickerActive = false;
20340
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
20341
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
20342
0
    {
20343
0
        g.DebugItemPickerBreakId = hovered_id;
20344
0
        g.DebugItemPickerActive = false;
20345
0
    }
20346
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
20347
0
        if (change_mapping && IsMouseClicked(mouse_button))
20348
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
20349
0
    SetNextWindowBgAlpha(0.70f);
20350
0
    if (!BeginTooltip())
20351
0
        return;
20352
0
    Text("HoveredId: 0x%08X", hovered_id);
20353
0
    Text("Press ESC to abort picking.");
20354
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
20355
0
    if (change_mapping)
20356
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
20357
0
    else
20358
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
20359
0
    EndTooltip();
20360
0
}
20361
20362
// [DEBUG] Stack Tool: update queries. Called by NewFrame()
20363
void ImGui::UpdateDebugToolStackQueries()
20364
35.9k
{
20365
35.9k
    ImGuiContext& g = *GImGui;
20366
35.9k
    ImGuiStackTool* tool = &g.DebugStackTool;
20367
20368
    // Clear hook when stack tool is not visible
20369
35.9k
    g.DebugHookIdInfo = 0;
20370
35.9k
    if (g.FrameCount != tool->LastActiveFrame + 1)
20371
35.9k
        return;
20372
20373
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
20374
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
20375
3
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
20376
3
    if (tool->QueryId != query_id)
20377
0
    {
20378
0
        tool->QueryId = query_id;
20379
0
        tool->StackLevel = -1;
20380
0
        tool->Results.resize(0);
20381
0
    }
20382
3
    if (query_id == 0)
20383
3
        return;
20384
20385
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
20386
0
    int stack_level = tool->StackLevel;
20387
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20388
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
20389
0
            tool->StackLevel++;
20390
20391
    // Update hook
20392
0
    stack_level = tool->StackLevel;
20393
0
    if (stack_level == -1)
20394
0
        g.DebugHookIdInfo = query_id;
20395
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20396
0
    {
20397
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
20398
0
        tool->Results[stack_level].QueryFrameCount++;
20399
0
    }
20400
0
}
20401
20402
// [DEBUG] Stack tool: hooks called by GetID() family functions
20403
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
20404
0
{
20405
0
    ImGuiContext& g = *GImGui;
20406
0
    ImGuiWindow* window = g.CurrentWindow;
20407
0
    ImGuiStackTool* tool = &g.DebugStackTool;
20408
20409
    // Step 0: stack query
20410
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
20411
0
    if (tool->StackLevel == -1)
20412
0
    {
20413
0
        tool->StackLevel++;
20414
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
20415
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
20416
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
20417
0
        return;
20418
0
    }
20419
20420
    // Step 1+: query for individual level
20421
0
    IM_ASSERT(tool->StackLevel >= 0);
20422
0
    if (tool->StackLevel != window->IDStack.Size)
20423
0
        return;
20424
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
20425
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
20426
20427
0
    switch (data_type)
20428
0
    {
20429
0
    case ImGuiDataType_S32:
20430
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
20431
0
        break;
20432
0
    case ImGuiDataType_String:
20433
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
20434
0
        break;
20435
0
    case ImGuiDataType_Pointer:
20436
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
20437
0
        break;
20438
0
    case ImGuiDataType_ID:
20439
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
20440
0
            return;
20441
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
20442
0
        break;
20443
0
    default:
20444
0
        IM_ASSERT(0);
20445
0
    }
20446
0
    info->QuerySuccess = true;
20447
0
    info->DataType = data_type;
20448
0
}
20449
20450
static int StackToolFormatLevelInfo(ImGuiStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
20451
0
{
20452
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
20453
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
20454
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
20455
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
20456
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
20457
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
20458
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
20459
0
        return (*buf = 0);
20460
#ifdef IMGUI_ENABLE_TEST_ENGINE
20461
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
20462
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
20463
#endif
20464
0
    return ImFormatString(buf, buf_size, "???");
20465
0
}
20466
20467
// Stack Tool: Display UI
20468
void ImGui::ShowStackToolWindow(bool* p_open)
20469
0
{
20470
0
    ImGuiContext& g = *GImGui;
20471
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20472
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
20473
0
    if (!Begin("Dear ImGui Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
20474
0
    {
20475
0
        End();
20476
0
        return;
20477
0
    }
20478
20479
    // Display hovered/active status
20480
0
    ImGuiStackTool* tool = &g.DebugStackTool;
20481
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20482
0
    const ImGuiID active_id = g.ActiveId;
20483
#ifdef IMGUI_ENABLE_TEST_ENGINE
20484
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
20485
#else
20486
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
20487
0
#endif
20488
0
    SameLine();
20489
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
20490
20491
    // CTRL+C to copy path
20492
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
20493
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
20494
0
    SameLine();
20495
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
20496
0
    if (tool->CopyToClipboardOnCtrlC && IsKeyDown(ImGuiMod_Ctrl) && IsKeyPressed(ImGuiKey_C))
20497
0
    {
20498
0
        tool->CopyToClipboardLastTime = (float)g.Time;
20499
0
        char* p = g.TempBuffer.Data;
20500
0
        char* p_end = p + g.TempBuffer.Size;
20501
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
20502
0
        {
20503
0
            *p++ = '/';
20504
0
            char level_desc[256];
20505
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
20506
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
20507
0
            {
20508
0
                if (level_desc[n] == '/')
20509
0
                    *p++ = '\\';
20510
0
                *p++ = level_desc[n];
20511
0
            }
20512
0
        }
20513
0
        *p = '\0';
20514
0
        SetClipboardText(g.TempBuffer.Data);
20515
0
    }
20516
20517
    // Display decorated stack
20518
0
    tool->LastActiveFrame = g.FrameCount;
20519
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
20520
0
    {
20521
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
20522
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
20523
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
20524
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
20525
0
        TableHeadersRow();
20526
0
        for (int n = 0; n < tool->Results.Size; n++)
20527
0
        {
20528
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
20529
0
            TableNextColumn();
20530
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
20531
0
            TableNextColumn();
20532
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
20533
0
            TextUnformatted(g.TempBuffer.Data);
20534
0
            TableNextColumn();
20535
0
            Text("0x%08X", info->ID);
20536
0
            if (n == tool->Results.Size - 1)
20537
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
20538
0
        }
20539
0
        EndTable();
20540
0
    }
20541
0
    End();
20542
0
}
20543
20544
#else
20545
20546
void ImGui::ShowMetricsWindow(bool*) {}
20547
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
20548
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
20549
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
20550
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
20551
void ImGui::DebugNodeFont(ImFont*) {}
20552
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
20553
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
20554
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
20555
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
20556
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
20557
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
20558
20559
void ImGui::DebugLog(const char*, ...) {}
20560
void ImGui::DebugLogV(const char*, va_list) {}
20561
void ImGui::ShowDebugLogWindow(bool*) {}
20562
void ImGui::ShowStackToolWindow(bool*) {}
20563
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
20564
void ImGui::UpdateDebugToolItemPicker() {}
20565
void ImGui::UpdateDebugToolStackQueries() {}
20566
20567
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
20568
20569
//-----------------------------------------------------------------------------
20570
20571
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
20572
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
20573
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
20574
#include "imgui_user.inl"
20575
#endif
20576
20577
//-----------------------------------------------------------------------------
20578
20579
#endif // #ifndef IMGUI_DISABLE